[問題] 關於=的多載..

看板C_and_CPP (C/C++)作者 (盜族)時間16年前 (2009/02/26 22:17), 編輯推噓3(307)
留言10則, 5人參與, 最新討論串1/1
以下是程式碼 #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(void) { cout << "window" << id << ": " << title << endl; } ~CWin(){delete[] title;} CWin(const CWin &win) { id=win.id; strcpy(title,win.title); } char get_id() { return this->id; } char get_title() { return this->title; } }; void operator=(CWin &w1,CWin &w2) { w1.get_id()=w2.get_id(); strcpy(w1.get_title(),w2.get_title()); return; } int main(void) { CWin win1('A',"main window"); CWin win2; win1.show(); win2.show(); operator=(win1,win2); win1.show(); system("pause"); return 0; } 在這個程式碼裡,我嘗試著想要把operator=當成一般函式來寫~ 但是卻無法編譯過,我想了很久不知道錯在哪邊 麻煩各位大大可以幫我看一下~謝謝!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.44.146.169

02/26 22:28, , 1F
get_id()回傳的是一個暫時的char變數
02/26 22:28, 1F

02/26 22:29, , 2F
對它做assign是不行的
02/26 22:29, 2F

02/26 22:29, , 3F
不好意思d大,我不太了解你的意思??
02/26 22:29, 3F

02/26 22:30, , 4F
喔喔...原來是這樣
02/26 22:30, 4F

02/26 22:30, , 5F
get_title的型態也錯了
02/26 22:30, 5F

02/26 22:36, , 6F
請問一下是哪邊錯呢..我是想要回傳char型態的title
02/26 22:36, 6F

02/26 22:52, , 7F
指標不熟的話建議你用string就好 回傳string&
02/26 22:52, 7F

02/26 22:53, , 8F
你的title是char*卻要當char回傳編譯不會過
02/26 22:53, 8F

02/26 23:33, , 9F
原來如此...謝謝h大及a大
02/26 23:33, 9F

02/28 02:03, , 10F
改成這樣 char & get_id(){} 應該就可以assign了
02/28 02:03, 10F
文章代碼(AID): #19fgHzqZ (C_and_CPP)
文章代碼(AID): #19fgHzqZ (C_and_CPP)