How to use operator= with anonymous objects in C++?

我只是一个虾纸丫 提交于 2019-12-07 11:25:56

问题


I have a class with an overloaded operator:

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

When I try to compile this:

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

I get the following error:

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&)

However, these two work fine (though they don't serve me any purpose):

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

-

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

What's going on? Am I assuming something incorrect about the way the assignment operator works?


回答1:


The right side of the assignment operator should take a const IPAddress&.

Temporary objects can be bound to const references, but not to non-const references. This is why x = IPAddress(IPV4, "192.168.2.10"); doesn't work.

IPAddress(IPV4, "192.168.2.10") = x; works because it is legal to invoke member functions on temporary objects.




回答2:


The assignment operator is defined using const:

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

Your temporary cannot bind to a non-const reference, as it is theoretically destructed before the call to the assignment operator (this might not happen due to optimization, don't rely on it).



来源:https://stackoverflow.com/questions/9265254/how-to-use-operator-with-anonymous-objects-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!