马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
using namespace std;
class father
{
public:
father(){cout<<"构造father\n";}
virtual void smart() //在这里加虚函数 程序报错,不加运行正常 为什么会这样?
{
cout<<"父亲很聪明\n";
}
//virtual void beautiful(){}
virtual ~father(){cout<<"析构father"<<endl;}
};
class mother
{
public:
mother(){cout<<"构造mother\n";}
virtual void beautiful(){cout<<"母亲很漂亮"<<endl;}
virtual ~mother(){cout<<"析构mother"<<endl;}
};
class son:public father,public mother
{
public:
son(){cout<<"构造son\n";}
virtual void beautiful(){cout<<"儿子也很帅\n";}
~son(){cout<<"析构son"<<endl;}
};
int main()
{
father *pf;
mother *pm;
int choice=0;
while (choice<99)
{
bool quit=false;
cout<<"(0)退出(1)父亲(2)儿子:";
cin>>choice;
switch(choice)
{
case 0:quit=true;
break;
case 1:pf=new father;
// pf->beautiful();
break;
case 2:pm=new son;
pm->beautiful();
pf->smart();//也就是这步奏出错,基类加虚函数,
delete pm;
default:cout<<"请输入从0到2之间的数字。";
}
if (quit)
{
break;
}
}
cout<<"程序结束"<<endl;
return 0;
}
//在基类加了虚函数为何错处,请大牛讲下,要细致点。这种程序是书上的,为何要这要做,是要我们明白什么?(难道是为了让我理解使用多态必须在基类的指针下,访问各个派生类?)
|