繁体   English   中英

运算符重载可以工作,但会导致堆栈溢出并在C ++中崩溃

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM