首页
社区
课程
招聘
为什么多态不对呢[求助]
发表于: 2005-12-9 14:55 4596

为什么多态不对呢[求助]

2005-12-9 14:55
4596
#include <stdio.h>
#include <vector>
using namespace std;
class Base
{
public :
        Base(){} ;
        virtual ~Base() {} ;
public :
        virtual void Draw() { printf("this is base Draw!") ;  };
};
class Deprived : public Base
{
public :
        Deprived() {} ;
        virtual ~Deprived() {} ;
public :
        void Draw() { printf("this is Deprived Draw!") ;  };

};

int main(int argc, char* argv[])
{
        vector<Base> objs ;
        Deprived dep ;
        objs.push_back(dep) ;
        for( vector<Base>::iterator it = objs.begin() ; it!= objs.end() ; it++ )
        {
                it->Draw() ;
        }
        return 0;
}

输出为:
this is base Draw!Press any key to continue
为什么没有调用继承类的方法呢?

[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)

收藏
免费 0
支持
分享
最新回复 (2)
雪    币: 190
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2
#include <stdio.h>
#include <vector>
using namespace std;
class Base
{

public :
        Base()        {        printf("this is base constructor!\n") ; } ;
        virtual ~Base() { printf("this is base deconstructor!\n") ;} ;
        Base(const Base& b)
        {
                printf("this is base copy constructor!\n") ;
        }
        const Base& operator=(const Base& b)
        {
                printf("this is base equal fun!\n") ;
                return *this ;
        }       
public :
        virtual void Draw()= 0  { printf("this is base Draw!\n") ;  };
};
class Deprived : public Base
{
public :
        Deprived() {printf("this is deprived constructor!\n") ;} ;
        Deprived(const Deprived& d) {printf("this is deprived copy constructor!\n") ;} ;
        virtual ~Deprived() {printf("this is deprived deconstructor!\n") ;} ;
        const Deprived& operator=(const Deprived& b) {
                printf("this is deprived equal fun!\n") ;
                return *this ;
        }         ;
public :
        void Draw()  { printf("this is Deprived Draw!\n") ;  };

};

int main(int argc, char* argv[])
{
        {
                vector< Base *> objs ;
                Deprived *dep = new Deprived() ;
                objs.push_back( dep ) ;
                for( vector<Base *>::iterator it = objs.begin() ; it!= objs.end() ; it++ )
                {
                        (*it)->Draw() ;
                        delete (*it)  ;
                }       
                objs.clear() ;
        }
        return 0;
}

输出为:
this is base constructor!
this is deprived constructor!
this is Deprived Draw!
this is deprived deconstructor!
this is base deconstructor!
Press any key to continue
虽然这样可以,但终觉不爽,哪位大侠给予指点,不甚感激!
2005-12-9 15:24
0
雪    币: 200
活跃值: (15)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
3
int main(int argc, char* argv[])
{
  Deprived dep ;
  Base b = dep;
  b.Draw();
  return 0;
}

和这个一样的。
2005-12-9 20:22
0
游客
登录 | 注册 方可回帖
返回
//