2012-03-30 101 views
0
#include<iostream> 

using namespace std; 

class Abc 
{ 
     public: 

     int a; 

     Abc() 
     { 
    cout<<"Def cstr called\n"; 
       a=0; 
     } 


     Abc(Abc &source) 
     { 
       a=source.a; 
       cout<<"copy constructor is called"<<endl; 
     } 
     void operator = (Abc &source) 
     { 
       a=source.a; 
       cout<<"overloaded assignment operator"<<endl; 
     } 
     Abc display(Abc ab) 
     { 
       cout<<"The a in display "<<ab.a<<endl; 
       return ab; 
     } 
}; 

int main() 

{ 

     Abc a; 

     Abc b; 

     a.a=10; 

     b=a; 

     cout<<"b.a ="<<b.a<<endl; 

     Abc x; 

     x = (a.display(b)); 

     return 0; 

} 

在行x =(a.display(b))中我收到編譯錯誤。在評論這條線時它有效。請幫助修改程序以便成功編譯它,並請告訴我在這裏出了什麼問題。由於複製構造函數導致的編譯錯誤

+0

什麼是確切的錯誤信息? – 2012-03-30 08:28:10

+0

http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree – Anonymous 2012-03-30 08:28:21

回答

1

你應該通過const引用來傳遞你的構造函數和賦值參數,而不是僅僅作爲參考:

即:

Abc(const Abc &source) { ... } 
const Abc& operator=(const Abc &source) { ... } 

可以(或可能不會)也想顯示是像這樣:

const Abc& display(const Abc &ab) 
{ 
     cout<<"The a in display "<<ab.a<<endl; 
     return ab; 
} 

旁白:儘管這些變化不會strictl Ÿ需要,他們會阻止一些棘手的錯誤 - 其中一個已運行到:

void operator = (Abc &source); 
Abc display(Abc ab); 

Abc a, b, x; 

x = (a.display(b)); 

這裏顯示返回一個臨時Abc,並operator=走的是一條非const Abc參考。 C++的一個奇怪規則是,你不能將一個非const引用綁定到一個臨時的 - 因此你的錯誤。

+0

謝謝安德森...現在它的工作。你能否請你解釋一下,爲什麼我們應該使它成爲常量。當它不是常量時,爲什麼會出現問題。謝謝 !!! – 2012-03-30 08:36:30

+0

感謝安德森.....它意味着,如果一個函數返回一個臨時值,如果我需要將該返回值傳遞給其他函數,那麼它應該有參數作爲常量引用。這只是一個慣例嗎?另外,如果我使void operator =(Abc source)和Abc(const Abc&source)那麼它可以工作,但如果在複製構造函數中我保留Abc(Abc&source),那麼它不起作用。對不起,如果我打擾你..你可以澄清這一點。 – 2012-03-30 08:56:13

1

編譯器引發錯誤,因爲將臨時對象分配給非const引用是非法的。在這種情況下的臨時對象是由a.display()返回的Abc對象,然後傳遞給賦值運算符。

充分利用參數拷貝構造函數和賦值操作符const

Abc(const Abc& source) { .. } 
void operator=(const Abc& source) { ... } 

注意,賦值運算符通常防止自賦值,並返回到自身的引用:

Abc& operator=(const Abc& source) 
{ 
    if (this != &source) 
    { 
     a = a.source; 
    } 
    return *this; 
} 
1

operator=不返回任何東西。起初它可能看起來並不直觀,但您需要返回對*this的引用,這可以讓您執行諸如a = b = c之類的操作。

const Abc & operator = (const Abc &source) 
{ 
    a=source.a; 
    cout<<"overloaded assignment operator"<<endl; 
    return *this; 
} 

此外,慣例是使用const引用(因爲你不希望改變原來的對象拷貝構造函數或operator=會)。

Abc(const Abc &source) { ... } 
... 
Abc & display(Abc &ab) { ... } 

我也改變了返回類型和參數display。基本上,只要可以,請使用參考。既然你返回的參數是一樣的,那麼可以這樣做。如果你正在函數中創建一個新的對象(但是在堆棧中,而不是字面上使用new),你必須返回一個值。

1

思想不知道你做了什麼錯誤訊息,我有幾個建議

//Make the parameter as constant 
      Abc(const Abc &source) 
      { 
        this.a=source.a; 
        cout<<"copy constructor is called"<<endl; 
      } 
//change the return type 
      ABC& operator = (const Abc &source) 
      { 
        cout<<"overloaded assignment operator"<<endl; 
        if (this == &source) 
          return *this; 
        this.a=source.a; 
        **// return the existing object** 
        return *this; 
      } 
相關問題