2013-04-11 150 views
1

我爲operator=重載了我創建的類。我爲兩個班級做了這個工作,其中一個工作得很好,他們都看起來是正確的。其中一個重載操作符不起作用。該程序不會產生任何錯誤,只是簡單地返回一個空白版本的類。如果任何人有任何想法可能是什麼問題,將不勝感激。重載=運算符

.h文件中

Patient operator=(const Patient &right); 

.cpp文件

//Overloaded functions 
Patient Patient::operator=(const Patient &right) 
{ 
    Patient temp; 

    temp.patientName = right.patientName; 
    temp.age = right.age; 
    temp.code = right.code; 
    temp.problem = right.problem; 
    temp.doctorName = right.doctorName; 
    temp.roomNum = right.roomNum; 
    temp.isWaiting = right.isWaiting; 
    temp.isComplete = right.isComplete; 

    return temp; 
} 

部分它被用於程序的。我意識到隨機輸出消息,我正試圖找到程序中我遇到問題的位置。縮小到pat=p;聲明。

void Room::setPat(Patient p) 
{ 
    cout << "Test" << endl; 
    cout << p.getName() << pat.getName() << "end"; 

    pat = p; 
    cout << p.getName() << pat.getName() << "end"; 
    cout << "End Test" << endl; 
    patUsed = true; 
} 
+5

你知道op =應該改變「this」對象,而不是一些臨時的? – PlasmaHH 2013-04-11 11:32:25

+0

謝謝你用笑聲開始新的一天。 ':'' – 2013-04-11 11:34:16

+0

除了@PlasmaHH表示,我認爲你也在做其他任務。你需要'p = pat;'這是'p.operator =(pat);' – Mahesh 2013-04-11 11:38:18

回答

1

你不需要「tmp」。只要刪除它。並返回一個參考。

Patient& Patient::operator=(const Patient &right) 
{ 
patientName = right.patientName; 
age = right.age; 
code = right.code; 
problem = right.problem; 
doctorName = right.doctorName; 
roomNum = right.roomNum; 
isWaiting = right.isWaiting; 
isComplete = right.isComplete; 
return *this; 
} 

你原來的代碼不修改=左操作數,與不期望的結果。

如果您Patient沒有其他成員這些,這=()的定義是不必要的,你可以忽略它。編譯器會爲您生成它,併爲每個成員「簡單」分配,如指向@sellibitze。只有當你需要別的東西時,你才能定義你的onw =(),例如深拷貝。我希望你不要在這裏複製任何指針,並且每個成員的類都有一個「正確的」=()。

+1

這不是他發佈的完全相同的代碼嗎? – PlasmaHH 2013-04-11 11:33:48

+0

我是否眯着眼睛,或者是這個代碼,粘貼在這個問題上? – Carsten 2013-04-11 11:34:28

+0

+1。我想補充一點,這樣一個運算符並不是真的有必要,因爲編譯器生成的運算符會做同樣的事情(成員智能副本)。 – sellibitze 2013-04-11 11:43:58

0

1)您無需在賦值運算符內創建任何臨時值。

2)賦值運算符應該返回一個對自身的引用。

示例here

 //Overloaded functions 
    Patient& Patient::operator=(const Patient &right) 
    { 
    patientName = right.patientName; 
    age = right.age; 
    code = right.code; 
    problem = right.problem; 
    doctorName = right.doctorName; 
    roomNum = right.roomNum; 
    isWaiting = right.isWaiting; 
    isComplete = right.isComplete; 
    return *this; 
    } 
0

問題是,您沒有設置當前對象的任何值,而只是創建一個新的並返回該值。

Patient& Patient::operator=(const Patient &right) 
{ 
    patientName = right.patientName; 
    age = right.age; 
    code = right.code; 
    problem = right.problem; 
    doctorName = right.doctorName; 
    roomNum = right.roomNum; 
    isWaiting = right.isWaiting; 
    isComplete = right.isComplete; 
    return *this; 
} 

請注意,局部變量已被刪除,而您將分配類變量和對當前類的引用。

2

從您提交的代碼判斷,無需編寫賦值運算符。編譯器生成的就好了。