#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..
C++重載虛擬+運算
我發現其原因被A2 + A3的表達的結果來作爲類型的對象aa,並且在下一個語句中,我們試圖將其轉換爲無效的派生類型對象,從而導致異常。所以我的問題是我們能否達到上述目的,即aa &a4 = a2 + a3;
以上功能有所變化?
你並不需要運營商=虛擬。 operator =返回引用而不是值。總的來說,任務是什麼? – Jagannath 2012-04-17 06:23:37