看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) DEV C++ 錯誤結果(Wrong Output): 編譯器出現"void operator=(CWin&, CWin&)' must be a nonstatic member function" 的錯誤 程式碼(Code):(請善用置底文網頁, 記得排版) #include<iostream> #include<cstdlib> using namespace std; class CWin { private: char id,*title; public: CWin(char i='D',char *text="Default window"):id(i) { title=new char[50]; strcpy(title,text); } void set_data(char i,char *text) { id=i; strcpy(title,text); } void show() { cout<<"Window "<<id<<": "<<title<<endl; } ~CWin() { delete [] title; } CWin(const CWin &win) { id=win.id; strcpy(title,win.title); } friend void operator=(CWin &win1,CWin &win2);//在類別裡宣告 }; void operator=(CWin &win1,CWin &win2)///類別外面定義 { win1.id=win2.id; strcpy(win1.title,win2.title); } int main() { CWin win1('A',"Main window"); CWin win2; win1.show(); win2.show(); operator=(win1,win2); cout<<endl<<"設定 win1=win2之後..."<<endl; win1.show(); win2.show(); win1.set_data('B',"hello window"); cout<<endl<<"更改win1的資料成員後..."<<endl; win1.show(); win2.show(); system("pause"); return 0; } 請問一下是哪邊出現了問題@@?? 謝謝大家 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.110.33.145 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1467532951.A.06D.html
LiloHuang: 根據 C++ 標準 13.5.3 描述,operator= 一定得是成員07/03 16:25
LiloHuang: 就像編譯器跟你描述的錯誤一樣,沒有兩個參數的版本07/03 16:26
可是這是書上的習題,還是書上說錯了@@? ※ 編輯: j19920816 (49.217.16.96), 07/03/2016 16:37:10
LiloHuang: 也許可以看一下書本是用什麼編譯器,使其可以編譯通過07/03 16:44
bibo9901: 即使可以, 回傳 void 也怪怪的07/03 17:27
jerryh001: 我們這邊也教用void 是有什麼優點嗎07/03 18:04
b0920075: 我們教的不是回傳void07/03 19:30
tyc5116: 這是單純測試嗎?不然用這樣的方式寫operator感覺怪怪的07/03 19:34
schizophrena: 為什麼operator可以在class外?07/03 19:35
schizophrena: 這樣不就不知道是哪個class會走這個operator?07/03 19:35
tyc5116: operator可以在class外阿07/03 19:42
LiloHuang: Binary operator 可以擺外面,由參數型別決定誰走進來07/03 20:06
LiloHuang: Copy assignment operator 則是得寫成非靜態成員函數07/03 20:07
LiloHuang: 通常會回傳自己的參考 (i.e. return *this);07/03 20:11
LiloHuang: 來達成 assignment chaining (i.e. a = b = c;)07/03 20:11
LiloHuang: 回傳用 void 就會阻礙 assignment chaining 的寫法07/03 20:21
我大概有點了解L大的說法,把void改成CWin在return *this 應該是這樣吧!? ※ 編輯: j19920816 (49.217.16.96), 07/04/2016 02:05:23
LiloHuang: 我指的是 CWin & 也就是 non-const reference to *this 07/04 07:06
LiloHuang: 回傳 CWin 會有多餘不必要的 copy constructor 呼叫 07/04 07:10
j19920816: 所以這題不能用friend了嗎?@@ 07/05 14:19
LiloHuang: 我認為不能用兩個參數的版本,除非編譯器有特異功能 XD 07/06 01:00