[英]Is “inline” implicit in C++ member functions defined in class definition
[英]C++: Implicit Member Functions
考慮下面我編寫的代碼:
#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&)
當我以Sample& getK(){return k;}
對here 2
進行更改時,它可以完美編譯。
有人可以解釋為什么嗎?
同樣在here 1
如果函數定義為Test& operator= (const Test& test){ k = test.getK(); cout << "Test Assignement Operator called" << endl; return (*this); }
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
為什么這樣?
首先,您的副本構造函數和賦值運算符采用非常量左值引用。 例如,
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;}
^^^^^
您已經定義了這些運算符:
Sample& Sample::operator= (Sample& s);
Test& Test::operator= (Test& test);
當a
是任何Sample
, a = b;
與a.operator= (b);
。 僅當b
是Sample&
有效。 getK
的返回值是一個臨時Sample
,不允許對臨時對象進行非常量左值引用(換句話說, Sample&
變量),請參見此問題 。
如果使getK
返回對Sample( Sample&
)的左值引用,則將其傳遞給賦值運算符沒有問題。 另外,如果您的賦值運算符采用const左值引用( const Sample&
),則將其綁定到臨時對象也沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.