0
我想知道在哪些情況下應該定義複製構造函數或賦值運算符。從我研究的內容可以看出,無論何時值通過值傳遞或通過值返回,都需要定義複製構造函數和重載賦值運算符。然而,當用於通過指針或引用(&)通/返回指針或引用,我們需要拷貝構造函數/重載賦值運算符關於複製構造函數和重載賦值運算符
class Sample
{
public :
// Assume a constructor that sets the node member
SampleNode * getNode()
{
return _node;
}
private:
SampleNode * node;
}
class SampleNode
{
public:
void getValue()
{
return _value;
}
private:
unsigned int value;
}
main()
{
Sample * ptr = new Sample(15);
SampleNode *node = getNode(); // Do we need a copy constructor here?
}
該代碼沒有意義。你會得到大量的編譯器錯誤。給出幾個問題:1.新樣本(15)不能工作。沒有適當的構造函數。 2.返回_node。身份不明的標識符_node。 3. getNode();身份不明的函數getNode。等等等等。 – thang
你的例子在技術上具有未定義的行爲(除非你修復它與編譯器錯誤一起),但要記住編譯器給你的一般工作,如果你做的事情是正確的。 – chris
您應該瞭解[三位法則](https://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29) – Nobody