[問題] 用operator=()改以friend來撰寫

看板C_and_CPP作者 (Kaung)時間8年前 (2016/07/03 16:02), 8年前編輯推噓10(1009)
留言19則, 7人參與, 最新討論串1/1
開發平台(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

07/03 16:25, , 1F
根據 C++ 標準 13.5.3 描述,operator= 一定得是成員
07/03 16:25, 1F

07/03 16:26, , 2F
就像編譯器跟你描述的錯誤一樣,沒有兩個參數的版本
07/03 16:26, 2F
可是這是書上的習題,還是書上說錯了@@? ※ 編輯: j19920816 (49.217.16.96), 07/03/2016 16:37:10

07/03 16:44, , 3F
也許可以看一下書本是用什麼編譯器,使其可以編譯通過
07/03 16:44, 3F

07/03 17:27, , 4F
即使可以, 回傳 void 也怪怪的
07/03 17:27, 4F

07/03 18:04, , 5F
我們這邊也教用void 是有什麼優點嗎
07/03 18:04, 5F

07/03 19:30, , 6F
我們教的不是回傳void
07/03 19:30, 6F

07/03 19:34, , 7F
這是單純測試嗎?不然用這樣的方式寫operator感覺怪怪的
07/03 19:34, 7F

07/03 19:35, , 8F
為什麼operator可以在class外?
07/03 19:35, 8F

07/03 19:35, , 9F
這樣不就不知道是哪個class會走這個operator?
07/03 19:35, 9F

07/03 19:42, , 10F
operator可以在class外阿
07/03 19:42, 10F

07/03 20:06, , 11F
Binary operator 可以擺外面,由參數型別決定誰走進來
07/03 20:06, 11F

07/03 20:07, , 12F
Copy assignment operator 則是得寫成非靜態成員函數
07/03 20:07, 12F

07/03 20:11, , 13F
通常會回傳自己的參考 (i.e. return *this);
07/03 20:11, 13F

07/03 20:11, , 14F
來達成 assignment chaining (i.e. a = b = c;)
07/03 20:11, 14F

07/03 20:21, , 15F
回傳用 void 就會阻礙 assignment chaining 的寫法
07/03 20:21, 15F
我大概有點了解L大的說法,把void改成CWin在return *this 應該是這樣吧!? ※ 編輯: j19920816 (49.217.16.96), 07/04/2016 02:05:23

07/04 07:06, , 16F
我指的是 CWin & 也就是 non-const reference to *this
07/04 07:06, 16F

07/04 07:10, , 17F
回傳 CWin 會有多餘不必要的 copy constructor 呼叫
07/04 07:10, 17F

07/05 14:19, , 18F
所以這題不能用friend了嗎?@@
07/05 14:19, 18F

07/06 01:00, , 19F
我認為不能用兩個參數的版本,除非編譯器有特異功能 XD
07/06 01:00, 19F
文章代碼(AID): #1NUCQN1j (C_and_CPP)