2014-02-27 68 views
0

考慮下面的代碼,我已經寫了:C++:隱成員函數

#include <iostream> 

using namespace std; 

class Sample{ 
    int a; 
    public: 
    Sample(){a=0;cout << "Sample Created (Default Constructor)" << endl;} 
    Sample(int n):a(n){cout << "Sample Created" << endl;} 
    ~Sample(){ cout << "Sample destroyed" << endl;} 
    Sample(Sample& s){a=s.getA(); cout << "Sample Copy Constructor called" << endl;} 
    Sample& operator= (Sample& s){this->a=s.getA(); cout << "Assignment Operator Called" << endl;return (*this);} 
    void setA(int n){ a=n;} 
    int getA(){return a;} 
    }; 

class Test{ 
    Sample k; 
    public: 
    Test(){ cout << "Test Created(Default Constructor)" << endl;} 
    Test(Sample& S):k(S){ cout << "Test Created" << endl;} 
    ~Test(){cout << "Test Destroyed" << endl;} 
    Test& operator= (Test& test){ k = test.getK(); cout << "Test Assignement Operator called" << endl; return (*this); } // Here 1 
    Test(Test& test){k=test.getK();cout << "Test Copy Constructor called" << endl;} 
    Sample getK(){return k;} // Here 2 
    void setK(Sample& s){k=s;} 
    }; 

int main() 
{ 
    Sample a1(5); 
    //Sample a2,a4; 
    //a2=a1=a4; 
    //Sample a3(a2); 
    Test b1(a1); 
    Test b2=b1; 
    //b2=b1; 

    return 0; 
    } 

我得到以下錯誤,而編譯:

$ g++ -Wall Interview.cpp -o Interview 
Interview.cpp: In member function `Test& Test::operator=(Test&)': 
Interview.cpp:23: error: no match for 'operator=' in '((Test*)this)->Test::k = Test::getK()()' 
Interview.cpp:12: note: candidates are: Sample& Sample::operator=(Sample&) 
Interview.cpp: In copy constructor `Test::Test(Test&)': 
Interview.cpp:24: error: no match for 'operator=' in '((Test*)this)->Test::k = Test::getK()()' 
Interview.cpp:12: note: candidates are: Sample& Sample::operator=(Sample&) 

當我更改here 2爲 - Sample& getK(){return k;}它編譯完美。

有人可以解釋爲什麼這樣嗎?

here 1

此外,如果函數定義爲Test& operator= (const Test& test){ k = test.getK(); cout << "Test Assignement Operator called" << endl; return (*this); }

我收到無差錯

$ g++ -Wall Interview.cpp -o Interview 
Interview.cpp: In member function `Test& Test::operator=(const Test&)': 
Interview.cpp:23: error: passing `const Test' as `this' argument of `Sample& Test::getK()' discards qualifiers 

爲什麼會這樣?

回答

3

首先,你的拷貝構造函數和賦值操作符帶有非const的左值引用。例如,

Test& operator= (Test& test) 

這意味着臨時變量不能作爲參數綁定到這些構造函數/運算符。規範簽名使用這個原因const引用,因爲它是沒有意義的變異操作數:

Test& operator= (const Test& test) 
       ^^^^^ 

這將使結合臨時工:

Test foo() { return Test(); } 

Test t0; 
t0 = foo(); 

其次,你的「干將」需要是const,使他們能夠在const實例調用,或通過const指針或引用:

Sample getK() const {return k;} 
       ^^^^^ 
1

您已經定義了這些運營商:

Sample& Sample::operator= (Sample& s); 
Test& Test::operator= (Test& test); 

a任何Samplea = b;是一樣的a.operator= (b);。這僅在bSample&時有效。來自getK的返回值是臨時的Sample,不允許參照this question與臨時變量的非常量左值引用(換句話說,Sample&變量)。

如果您使getK返回樣本(Sample&)的左值引用,那麼將它傳遞給您的賦值運算符沒有任何問題。或者,如果您的賦值運算符采用常量左值引用(const Sample&),將其綁定到臨時對象將沒有問題。