2013-03-01 134 views
2

爲什麼這個代碼:爲什麼重載的賦值操作符不會被繼承?

class X { 
public: 
    X& operator=(int p) { 
     return *this; 
    } 
    X& operator+(int p) { 
     return *this; 
    } 
}; 

class Y : public X { }; 

int main() { 
    X x; 
    Y y; 
    x + 2; 
    y + 3; 
    x = 2; 
    y = 3; 
} 

給錯誤:

prog.cpp: In function ‘int main()’: 
prog.cpp:14:9: error: no match for ‘operator=’ in ‘y = 3’ 
prog.cpp:14:9: note: candidates are: 
prog.cpp:8:7: note: Y& Y::operator=(const Y&) 
prog.cpp:8:7: note: no known conversion for argument 1 from ‘int’ to ‘const Y&’ 
prog.cpp:8:7: note: Y& Y::operator=(Y&&) 
prog.cpp:8:7: note: no known conversion for argument 1 from ‘int’ to ‘Y&&’ 

爲什麼+運營商繼承,但=運營商呢?

+2

回答你的問題是[這裏](http://stackoverflow.com/questions/12009865/operator-和函數 - 不是繼承在 - c) – 2013-03-01 13:36:56

回答

9

Y包含隱式聲明的賦值運算符,它隱藏了在基類中聲明的運算符。通常,在派生類中聲明一個函數會隱藏在基類中聲明的具有相同名稱的任何函數。

如果你想既提供Y,使用using聲明:

class Y : public X { 
public: 
    using X::operator=; 
}; 
+0

如果類「Y」需要「擴展」運算符'=',即比父類中的return * this做更多的事情? – Ignorant 2015-12-07 17:35:07

+0

然後你自己重寫它,就像你最初做的那樣,不要使用繼承。我個人發現使用虛擬操作符過載並不總是最好的 – Curious 2016-01-01 00:00:23

0

如果未聲明編譯器自動生成的方法,則會忘記它們。作業是其中之一。

+0

爲什麼自動生成刪除我的定義,當他們有不同的簽名? – Eric 2013-03-01 13:38:36

+0

@Eric:它不會刪除它,它會隱藏它。 – 2013-03-01 13:38:49

+0

@AndyProwl:同樣的問題然後:爲什麼它隱藏它,當簽名不衝突? – Eric 2013-03-01 13:39:40