[英]Operator Overloading working but giving stack overflow and crashing in C++
我寫了這個Node類和=運算符重載函數,這是我可以編譯和運行它的唯一方法,但是它溢出並轟炸了我的程序。 有人可以修復它以便工作。 我對C ++中的重載運算符沒有太多經驗。 我只想將一個Node對象設置為等於另一個Node對象。 提前致謝!
class Node
{
public:
Node();
int y;
Node& operator=(const Node& n);
};
Node::Node(){ y = -1; }
Node& Node::operator=(const Node& n) { return *this = n; }
。
Build issues:
1>c:\users\aaron mckellar\documents\school stuff\cs445\test\test\main.cpp(57) : warning C4717: 'Node::operator=' : recursive on all control paths, function will cause runtime stack overflow
1>Linking...
1>LINK : C:\Users\Aaron McKellar\Documents\School Stuff\CS445\Test\Debug\Test.exe not found or not built by the last incremental link; performing full link
在您的operator=
您需要完成將成員變量設置為等於傳入的Node值的工作。
Node& Node::operator=(const Node& n)
{
y = n.y;
return *this;
}
您用英語所做的相應示例:狗的定義是狗。 不用說狗的定義是狼的馴養形式,而是食肉目科的犬科的成員。
您具有無限遞歸,因為* this = n正在調用Node :: operator =()(因為這是一個Node)。 賦值運算符的通常行為就像一個復制構造函數,但是您必須檢查自我賦值。 請參閱: http : //www.parashift.com/c++-faq-lite/assignment-operators.html
只需刪除有問題的功能。 C ++為您定義了一個默認的operator=
。 該函數在每種意義上都是“那里”:您可以得到一個指向它的指針,等等。但是,如果添加一個重載,則默認值將完全消失,並且在其中使用=
會導致遞歸。
如果您確實有其他功能要添加到operator=
,那么您也必須自己實現默認功能,即y = ny;
。 您的重載將殺死默認值=
因此*this=n
除了調用自身外,沒有其他事情。
如果您有很多數據成員,一種替代方法是聲明一個類,僅使用其默認的operator=
:
struct Node_data { // "POD" struct for just data, no methods
int q,r,s,t,u,v,w,x,y,z; // rough example ;v)
};
class Node : public Node_data {
…
Node & Node::operator=( const Node &n ) {
Node_data::operator=( n ); // compiler-generated func
cout << "operator= called" << endl;
}
};
您的問題是Node::operator=(const Node& n)
包含return *this = n;
。 return *this = n;
之所以調用operator=
是因為您在類的實例和類的另一個實例上使用=。
您的重載運算符就是如下所示的代碼:
node = someothernode;
由於“ * nodeptr”等效於“ node”,因此您創建了一個調用自身的運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.