#include <iostream>
using namespace std;
class A
{
protected:
int a,b;
public:
A(int aa, int bb):a(aa), b(bb) {}
void printA(){
cout<<"a: "<<a<<"\tb: "<<b<<endl;
}
};
class B: public A
{
int c;
public:
B(int aa, int bb, int cc):A(aa,bb),c(cc) {}
void printB()
{
cout<<"a: "<<a<<"\tb: "<<b<<"\tc: "<<c<<endl;
}
};
int main()
{
A a(1,1);
B b(2,3,4);
A &r1=a;
A &r2=b;
r1.printA();
r2.printA();
//r2.printB();
return 0;
}
运行结果:
过程分析:
运行错误 原因r2.printA()
r2不能调用printA
将r2.printA()注释 运行结果如图
本文通过一个 C++ 示例展示了类继承与多态的概念。代码中定义了两个类 A 和 B,其中 B 类继承自 A 类。通过指向不同基类对象的引用调用成员函数,演示了多态的特性。

被折叠的 条评论
为什么被折叠?



