[問題] 用operator=()改以friend來撰寫
開發平台(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
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
07/03 17:27, 4F
推
07/03 18:04, , 5F
07/03 18:04, 5F
推
07/03 19:30, , 6F
07/03 19:30, 6F
推
07/03 19:34, , 7F
07/03 19:34, 7F
推
07/03 19:35, , 8F
07/03 19:35, 8F
→
07/03 19:35, , 9F
07/03 19:35, 9F
推
07/03 19:42, , 10F
07/03 19:42, 10F
推
07/03 20:06, , 11F
07/03 20:06, 11F
→
07/03 20:07, , 12F
07/03 20:07, 12F
→
07/03 20:11, , 13F
07/03 20:11, 13F
→
07/03 20:11, , 14F
07/03 20:11, 14F
→
07/03 20:21, , 15F
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
07/04 07:06, 16F
→
07/04 07:10, , 17F
07/04 07:10, 17F
→
07/05 14:19, , 18F
07/05 14:19, 18F
推
07/06 01:00, , 19F
07/06 01:00, 19F