[英]Override the assignment operator in the inheriting class
class A
{
int Avalue;
A& operator=(A& copyMe)
{
Avalue = copyMe.Avalue;
return *this;
}
}
class B:public A
{
int Bvalue;
B& operator=(B& copyMe)
{
Bvalue = copyMe.Bvalue
return *this;
}
}
如何從B的賦值運算符調用A或基類賦值運算符?。如何從賦值運算符調用處理A的返回引用。
所有運算符都可以被認為是一些聰明的函數,但這只是編譯器的禮貌,它足夠聰明地推斷出給定的操作數是什么並將它們傳遞給你的覆蓋。 這是一種很好的可擴展方法,可以在有意義的情況下添加好的語法糖,但是由於它們通常的用法,人們不能真正看到它是有效的,但是當你觀察到覆蓋的定義時,它們看起來像功能並且表現得像職能。 因此,只需使用范圍運算符::
來訪問A接口的公共部分。
A::operator=(copyMe)
請注意,您缺少幾個分號,並且類默認為private
訪問。 要訪問A中的復制賦值運算符,您需要將其指定為public:
class A
{
private:
int Avalue;
public:
A& operator=(A& copyMe)
{
Avalue = copyMe.Avalue;
return *this;
}
}
使用范圍運算符顯式調用賦值運算符(或任何其他函數):A :: operator =(someval);
查看: http : //en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
您只需要在派生的op中添加A::operator=(copyMe)
。 此外,副本應該是非const引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.