作者starmovie (盜族)
看板C_and_CPP
標題[問題] 關於=的多載..
時間Thu Feb 26 22:17:32 2009
以下是程式碼
#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
1F:推 dendrobium:get_id()回傳的是一個暫時的char變數 02/26 22:28
2F:→ dendrobium:對它做assign是不行的 02/26 22:29
3F:→ starmovie:不好意思d大,我不太了解你的意思?? 02/26 22:29
4F:→ starmovie:喔喔...原來是這樣 02/26 22:30
5F:→ akasan:get_title的型態也錯了 02/26 22:30
6F:→ starmovie:請問一下是哪邊錯呢..我是想要回傳char型態的title 02/26 22:36
7F:推 hylkevin:指標不熟的話建議你用string就好 回傳string& 02/26 22:52
8F:→ hylkevin:你的title是char*卻要當char回傳編譯不會過 02/26 22:53
9F:→ starmovie:原來如此...謝謝h大及a大 02/26 23:33
10F:推 aaa12345:改成這樣 char & get_id(){} 應該就可以assign了 02/28 02:03