#include <iostream>
class aa
{
public:
aa(){}
aa(aa& obj)
{
aa1 = obj.aa1;
}
virtual aa operator =(aa& obj)
{
aa1 = obj.aa1;
return (*this);
}
virtual aa operator +(aa& obj)
{
aa1 += obj.aa1;
return (*this);
}
int aa1;
};
class bb: public aa
{
public:
bb():aa(){}
bb(bb& obj)
{
bb1 = obj.bb1;
}
aa operator =(aa& obj)
{
aa::operator =(obj);
bb b1 = dynamic_cast<bb&>(obj);
bb1 = b1.bb1;
return (*this);
}
aa operator +(aa& obj)
{
aa::operator +(obj);
bb b1 = dynamic_cast<bb&>(obj);
bb1 += b1.bb1;
return (*this);
}
int bb1;
};
int main()
{
bb b1;
bb b2;
b1.bb1 = 1;
b1.aa1 = 1;
b2.bb1 = 2;
b2.aa1 = 2;
aa &a1 = b1;
aa &a2 = b2;
a1 = a2;
b1 = dynamic_cast<bb&>(a1);
b2 = dynamic_cast<bb&>(a2);
std::cout<<b1.aa1<<";"<<b1.bb1;
bb b3;
b3.bb1 = 3;
b3.aa1 = 3;
aa &a3 = b3;
aa &a4 = a2 + a3;
b3 = dynamic_cast<bb&>(a4);
return 0;
}
输出:
2;2
然后它在b3 = dynamic_cast<bb&>(a4);
给出错误的行崩溃std::bad_cast at memory location 0x0012fdbc..
我发现的原因是 a2+a3 的表达式结果作为 aa 类型的对象出现,在下一个语句中,我们试图将其强制转换为无效的派生类型对象,从而导致异常。所以我的疑问是我们能否实现上述意图,即aa &a4 = a2 + a3;
对上述功能进行一些更改?