全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:1943
推到 Plurk!
推到 Facebook!

operator=()使用friend函數來撰寫

答題得分者是:GrandRURU
j19920816
一般會員


發表:3
回覆:0
積分:0
註冊:2015-08-01

發送簡訊給我
#1 引用回覆 回覆 發表時間:2016-07-03 15:45:28 IP:123.110.xxx.xxx 訂閱
小弟最近在學C++碰到一個習題的問題:將operator=()使用friend函數來撰寫
以下是程式碼,我把函式宣告在類別裡,定義在類別外,可是編譯器一直過不了,一直出現
void operator=(CWin&, CWin&)' must be a nonstatic member function 的錯誤,可否大大幫我解惑一下哪裡出錯了??




#include
#include
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 "< }
~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< win1.show();
win2.show();

win1.set_data('B',"hello window");
cout< win1.show();
win2.show();


system("pause");
return 0;
}
編輯記錄
j19920816 重新編輯於 2016-07-04 10:59:22, 註解 無‧
j19920816 重新編輯於 2016-07-04 10:59:58, 註解 無‧
j19920816 重新編輯於 2016-07-04 11:01:06, 註解 無‧
j19920816 重新編輯於 2016-07-04 11:01:56, 註解 無‧
j19920816 重新編輯於 2016-07-04 11:02:23, 註解 無‧
j19920816 重新編輯於 2016-07-04 11:03:10, 註解 無‧
j19920816 重新編輯於 2016-07-04 11:04:45, 註解 無‧
j19920816 重新編輯於 2016-07-04 11:05:58, 註解 無‧
GrandRURU
站務副站長


發表:240
回覆:1680
積分:1874
註冊:2005-06-21

發送簡訊給我
#2 引用回覆 回覆 發表時間:2023-04-28 08:42:35 IP:59.120.xxx.xxx 未訂閱
您的程式碼有一個錯誤:您沒有在 CWin 類別中定義運算子= (operator=)。因此,當您宣告這個函式為友元函式時,編譯器無法將其識別為 CWin 類別的成員函式。
要解決這個問題,您可以將運算子= (operator=) 定義為 CWin 類別的成員函式。這樣可以保證編譯器能夠正確識別這個函式是 CWin 類別的成員,也可以讓它直接訪問 CWin 物件的私有成員。
以下是修改後的程式碼:

[code cpp]
#include
#include
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;
title = new char[50];
strcpy(title, win.title);
}

CWin& operator=(const CWin& win)
{
id = win.id;
strcpy(title, win.title);
return *this;
}
};

int main()
{
CWin win1('A', "Main window");
CWin win2;

win1.show();
win2.show();

win2 = win1;
win1.show();
win2.show();

win1.set_data('B', "Hello window");
win1.show();
win2.show();

system("pause");
return 0;
}
[/code]
在這個程式碼中,我們將運算子= (operator=) 定義為 CWin 類別的成員函式,並將其宣告為 const CWin& win。這樣可以讓運算子= (operator=) 接受 const CWin 物件作為參數,避免了對傳入參數的意外更改。同時,我們還修改了 CWin 的複製建構造函式 (copy constructor) 和解構函式 (destructor),以避免記憶體泄漏的問題。
系統時間:2024-04-27 13:12:46
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!