【发布时间】:2023-03-23 05:22:01
【问题描述】:
class A{
public:
int aaa;
A(){aaa=0};
void print() const;
};
class B : public A{
public:
int bbb;
B(){aaa=0,bbb=12};
void print() const;
};
void A::print() const{
cout << aaa << endl;
}
void B::print() const{
cout << bbb << endl;
}
int main(){
A *ptr[2];
ptr[0]=new B();
ptr->print(); //it will show 0 from aaa but how to show 12 from bbb.
}
我想在 A 类中显示 12(在 B 类中:公共 A)而不是 0。 有人知道很多指针和继承和多态性,请帮助我知道如何感谢!
【问题讨论】:
-
您的代码无法编译。 “错误:预期';' '}' 之前的两个位置。
-
将接受的答案的“虚拟”修饰符添加到 A::print() 后,您仍然可以使用显示的“ptr[0]->A::print()”访问 A::print A::aaa 的“0”。
标签: c++ pointers inheritance polymorphism