[問題] C++運算子重載和繼承合用,會導致混亂
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
cygwin64
問題(Question):
最近正在省思我要把C++定位成怎樣的工具
C++的多功能的確很容易導致誤用
現在寫C++時我都會把"避免過度設計"這句話放在心中
以上都是題外話,我要向各位請教的是C++技術上的問題
之所以說上面這些屁話,是因為這個問題是在思索上面的哲學問題而發現的
下方的程式碼,類A定義了operator*和operator+
類B繼承自類A,因為方便直接沿用類A的operator+,但定義了自己的operator*
最後在main函數中宣告兩個B實例b1和b2,並執行(b2+b1)*3.0
直觀上會以為operator*是調用類B的
但事實上是調用類A的,因為在執行operator+時回傳的是A reference
想請問C++老手,這樣的問題是用什麼方法解決?
做type conversion,多型,還是單純不要亂用operator overload?
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <iostream>
using namespace std;
class A
{
public:
A& operator+(const A& rhs){cout<<"A& A::operator+(const A&)\n";}
A& operator*(const double& rhs){cout<<"A& A::operator*(const double&)\n";}
};
class B: public A
{
public:
B& operator*(const double& rhs){cout<<"B& B::operator*(const double&)\n";}
B& operator=(const A& rhs){cout<<"B& B::operator=(const A&)\n";}
B& operator=(const B& rhs){cout<<"B& B::operator=(const B&)\n";}
};
int main()
{
B b1, b2;
b1=(b2+b1)*3.0;
/*
output:
A& A::operator+(const A&)
A& A::operator*(const double&)
B& B::operator=(const A&)
*/
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.120.19.5
※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1402208713.A.FD2.html
※ 編輯: frankhsu421 (140.120.19.5), 06/08/2014 14:28:38
→
06/08 15:24, , 1F
06/08 15:24, 1F
→
06/08 15:31, , 2F
06/08 15:31, 2F
推
06/08 15:43, , 3F
06/08 15:43, 3F
→
06/08 15:48, , 4F
06/08 15:48, 4F
推
06/08 15:49, , 5F
06/08 15:49, 5F
→
06/08 15:59, , 6F
06/08 15:59, 6F
推
06/08 16:25, , 7F
06/08 16:25, 7F
→
06/08 16:26, , 8F
06/08 16:26, 8F
→
06/08 16:27, , 9F
06/08 16:27, 9F
→
06/08 16:28, , 10F
06/08 16:28, 10F
→
06/08 16:29, , 11F
06/08 16:29, 11F
→
06/08 16:30, , 12F
06/08 16:30, 12F
→
06/08 16:30, , 13F
06/08 16:30, 13F
→
06/08 16:33, , 14F
06/08 16:33, 14F
→
06/08 16:36, , 15F
06/08 16:36, 15F
→
06/08 16:37, , 16F
06/08 16:37, 16F
→
06/08 16:39, , 17F
06/08 16:39, 17F
→
06/08 16:41, , 18F
06/08 16:41, 18F
推
06/08 16:48, , 19F
06/08 16:48, 19F
→
06/08 16:48, , 20F
06/08 16:48, 20F
推
06/08 19:57, , 21F
06/08 19:57, 21F
→
06/08 19:58, , 22F
06/08 19:58, 22F
→
06/08 19:58, , 23F
06/08 19:58, 23F
→
06/08 20:22, , 24F
06/08 20:22, 24F
推
06/09 01:54, , 25F
06/09 01:54, 25F
→
06/09 12:45, , 26F
06/09 12:45, 26F
→
06/09 12:46, , 27F
06/09 12:46, 27F
→
06/09 12:46, , 28F
06/09 12:46, 28F
→
06/09 12:47, , 29F
06/09 12:47, 29F
→
06/09 13:23, , 30F
06/09 13:23, 30F
→
06/09 13:24, , 31F
06/09 13:24, 31F