如何在C ++中使用operator = with匿名对象?

时间:2012-02-13 17:43:49

标签: 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"));

发生了什么事?我是否假设分配算子的工作方式不正确?

2 个答案:

答案 0 :(得分:5)

赋值运算符的右侧应采用const IPAddress&

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

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

答案 1 :(得分:4)

赋值运算符使用const

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

你的临时无法绑定到非const引用,因为它在调用赋值运算符之前理论上是被破坏的(这可能不是由于优化而发生的,不依赖它)。

相关问题