猿问

你好,咨询一个问题,是关于C++ class的

class A
{
public:
void virtual read()
{
cout<<"base class A";
}
};
class B:public A
{
public:
void read()
{
cout<<"derived class B";
}
};
int main()
{
B obj();
clrscr();
obj.read();
getch();
}
/*int main()
{
B obj;
obj.read();
return 0;
}*/
int main()
{
B obj;
obj.A::read();
cout<<"\n";
obj.B::read();
return 0;
}
/*int main()
{
A obj1;
B obj2;
A*ptr;
ptr=&obj1;
ptr->read();
cout<<"\n";
ptr=&obj2;
ptr->read();
return 0;
}*/
麻烦请详细的解释每句。

www说
浏览 382回答 2
2回答

临摹微笑

class A//A类声名{public://公共成员void virtual read()//read的虚函数{cout<<"base class A";//输出“base class A”}};class B:public A//B类声名,继承A{public:void read()//重写read(必须重写,因为前面是虚函数){cout<<"derived class B";//输出“derived class B”}};int main()//主程序进入{B obj();//建立B类的obj对象clrscr();//调用clrscr(你给的代码里没有这个的声名)obj.read();//调用obj对象的read对象getch();}//以下部分全是你本来有的注释/*int main(){B obj;obj.read();return 0;}*/int main(){B obj;obj.A::read();cout<<"\n";obj.B::read();return 0;}/*int main(){A obj1;B obj2;A*ptr;ptr=&obj1;ptr->read();cout<<"\n";ptr=&obj2;ptr->read();return 0;}*/

小怪兽爱吃肉

不知道这么多main函数干嘛的,就是多态性测试吧,让基类对象指针指向派生类的read函数class A{public:void virtual read()//虚函数{cout<<"base class A";}};class B:public A{public:void read()//继承 实现虚函数{cout<<"derived class B";}};void main(){A *a;//基类指针B obj;//派生类对象a=&obj;//动态编联 调用派生类的read函数a->read();//输出derived class Bgetch();}
随时随地看视频慕课网APP
我要回答