【问题标题】:How to use operator= with anonymous objects in C++?如何在 C++ 中将 operator= 与匿名对象一起使用?
【发布时间】:2012-03-05 03:13:23
【问题描述】:

我有一个带有重载运算符的类:

IPAddress& IPAddress::operator=(IPAddress &other) {
    if (this != &other) {
        delete data;
        this->init(other.getVersion());
        other.toArray(this->data);
    }
    return *this;
}

当我尝试编译时:

IPAddress x;
x = IPAddress(IPV4, "192.168.2.10");

我收到以下错误:

main.cc: In function ‘int main()’:
main.cc:43:39: error: no match for ‘operator=’ in ‘x = IPAddress(4, ((const std::string&)(& std::basic_string<char>(((const char*)"192.168.2.10"), ((const std::allocator<char>&)((const std::allocator<char>*)(& std::allocator<char>())))))))’
IPAddress.h:28:20: note: candidate is: IPAddress& IPAddress::operator=(IPAddress&)

但是,这两个工作正常(尽管它们对我没有任何用途):

IPAddress x;
IPAddress(IPV4, "192.168.2.10") = x;

-

IPAddress x;
x = *(new IPAddress(IPV4, "192.168.2.10"));

发生了什么事?我是否假设赋值运算符的工作方式不正确?

【问题讨论】:

    标签: c++ methods operator-overloading


    【解决方案1】:

    赋值运算符的右边应该是const IPAddress&amp;

    临时对象可以绑定到 const 引用,但不能绑定到非 const 引用。这就是x = IPAddress(IPV4, "192.168.2.10"); 不起作用的原因。

    IPAddress(IPV4, "192.168.2.10") = x; 之所以有效,是因为在临时对象上调用成员函数是合法的。

    【讨论】:

    • 谢谢,它成功了。我只需要将 operator= 调用的其他一些方法更改为 const。
    【解决方案2】:

    赋值运算符是使用const定义的:

    IPAddress& IPAddress::operator=(const IPAddress &other)
    

    您的临时值不能绑定到非常量引用,因为理论上它在调用赋值运算符之前已被破坏(由于优化,这可能不会发生,不要依赖它)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-17
      • 2012-05-20
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多