【问题标题】:c++ assignment operator, how can you set one object to be equal to an instance of a new object?c++赋值运算符,如何设置一个对象等于一个新对象的实例?
【发布时间】:2015-10-28 14:44:00
【问题描述】:
struct Object{
    size_t num;

    Object(size_t s){
        num = s;
    }

    Object(string str){
        num = 1;
    }

    Object& operator = (const Object& b){
        cout << "assignemnt constructor called" << endl;
        return *this;
    }
};


int main ()
{
    Object b2{ 5 };
    Object b3("str");
    b2 = b3;
    b3 = Object(2);   //<-------------how can you set b3 to be Object(2)?
}

我正在尝试将一个对象设置为等于一个新对象。但是在这个例子中 b3 没有改变。可以帮助我了解如何让 b3 成为一个新对象(2)。谢谢

【问题讨论】:

  • 好吧,你实现了一个赋值运算符,你得到了你实现的行为。除了你自己,你没有人可以责备。
  • here

标签: c++ object constructor assignment-operator


【解决方案1】:

您的赋值运算符并没有真正进行任何赋值。您可能想要做的是:

Object& operator = (const Object& b){
    cout << "assignemnt constructor called" << endl;
    num = b.num;
    return *this;
}

另外,文本“Assignment constructor called”也不正确。这是赋值运算符,而不是复制构造函数。当你这样做时:

b3 = Object(2);

您调用赋值运算符。相反,当你这样做时:

Object b3 = Object(2)

您调用复制构造函数。一个微妙但重要的区别。

【讨论】:

    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 2018-12-13
    • 1970-01-01
    • 2013-10-13
    相关资源
    最近更新 更多