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

作者: j19920816 (Kaung)   2016-07-03 16:02:28
開發平台(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;
}
請問一下是哪邊出現了問題@@?? 謝謝大家
作者: LiloHuang (十年一刻)   2016-07-03 16:25:00
根據 C++ 標準 13.5.3 描述,operator= 一定得是成員就像編譯器跟你描述的錯誤一樣,沒有兩個參數的版本也許可以看一下書本是用什麼編譯器,使其可以編譯通過
作者: bibo9901 (function(){})()   2016-07-03 17:27:00
即使可以, 回傳 void 也怪怪的
作者: jerryh001   2016-07-03 18:04:00
我們這邊也教用void 是有什麼優點嗎
作者: b0920075 (Void)   2016-07-03 19:30:00
我們教的不是回傳void
作者: tyc5116 (累人啊....)   2016-07-03 19:34:00
這是單純測試嗎?不然用這樣的方式寫operator感覺怪怪的
作者: schizophrena (你很記者你很腦殘)   2016-07-03 19:35:00
為什麼operator可以在class外?這樣不就不知道是哪個class會走這個operator?
作者: tyc5116 (累人啊....)   2016-07-03 19:42:00
operator可以在class外阿
作者: LiloHuang (十年一刻)   2016-07-03 20:06:00
Binary operator 可以擺外面,由參數型別決定誰走進來Copy assignment operator 則是得寫成非靜態成員函數通常會回傳自己的參考 (i.e. return *this);來達成 assignment chaining (i.e. a = b = c;)回傳用 void 就會阻礙 assignment chaining 的寫法
作者: j19920816 (Kaung)   2016-07-05 14:19:00
所以這題不能用friend了嗎?@@
作者: LiloHuang (十年一刻)   2016-07-06 01:00:00
我認為不能用兩個參數的版本,除非編譯器有特異功能 XD

Links booklink

Contact Us: admin [ a t ] ucptt.com