如何在C ++中对匿名对象使用operator =? [英] How to use operator= with anonymous objects in C++?
问题描述
我有一个带有重载运算符的类:
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;
}
当我尝试编译时:
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&)
但是,这两个都可以正常工作(尽管它们对我没有任何作用):
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?
推荐答案
赋值运算符的右侧应为const IPAddress&
.
The right side of the assignment operator should take a const IPAddress&
.
临时对象可以绑定到const引用,但不能绑定到非const引用.这就是x = IPAddress(IPV4, "192.168.2.10");
无法正常工作的原因.
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;
之所以起作用,是因为在临时对象上调用成员函数是合法的.
IPAddress(IPV4, "192.168.2.10") = x;
works because it is legal to invoke member functions on temporary objects.
这篇关于如何在C ++中对匿名对象使用operator =?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!