c++ - 如何在 C++ 中将 operator= 与匿名对象一起使用?

标签 c++ methods operator-overloading

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

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"));

这是怎么回事?关于赋值运算符的工作方式,我是否假设有什么不正确的地方?

最佳答案

赋值运算符的右边应该取一个const IPAddress&

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

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

关于c++ - 如何在 C++ 中将 operator= 与匿名对象一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265254/

相关文章:

c++ - 指向常量数组的指针的正确定义是什么?

java - 将军事时间加在一起不起作用 - JAVA

java - 为什么我的 Eclipse 程序终止?

c# - 允许一个方法只接受数字?

c++ - 数组元素中的 C++ 逻辑错误,而数组作为构造函数中的参数传递

c++ - C++中Couchdb的库?

c++ - 如何静态和动态链接C/C++库

c++ - LINK2019 中对运算符>> 的 undefined reference 结果

c++ - 派生赋值运算符从基数调用

c++ - C++ 是如何解析这个返回类型的?