C++基类和派生类赋值问题
#include <iostream>
using namespace std;
class A
{
private:
int i;
public:
A()
{
i = 0;
}
A(int t)
{
i = t;
}
A(A &aa)
{
i = aa.i;
}
void show() const
{
cout << "i: " << i << endl;
}
};
class B:public A
{
private:
int x;
int y;
public:
B()
{
x = 0;
y = 0;
}
B(int t1, int t2, int t3):A(t3)
{
x = t1;
y = t2;
}
void show() const
{
cout << "x: " << x << endl;
cout << "y: " << y << endl;
A::show();
}
};
int main()
{
A aa(60);
aa.show();
cout<< endl;
B bb(90,20,800);
bb.show();
cout << endl;
A aa1;
aa1 = bb; //为什么bb可以赋值给aal
aa1.show();
return 0;
}
根据你的调用 所以 aa.show()输出i为800不奇怪了
[解决办法]
很基础的派生问题:这种直接赋值得益于编译器的处理,编译器会把B中A的部分赋值给A。如5楼所解释那样。A是交通工具,有个属性i:可以行使,B是辆保时捷,它有x属性:豪车,y属性:4个轮子,它也具备i属性:飞速行使。这样,aa1 = bb; 就不难理解了。所以,aa1这个交通工具不一般:可以飞速行使。