我正在查看重载运算符=。
为什么我可以设置'this ==&st'但不能设置'* this == st'?
StringBad & StringBad::operator=(const StringBad & st)
{
if (this == &st) // if the object assigned to itself, return to itself.
return *this; // why compiler give error when I set *this ==st ?
/* blah blah
...
... */
return *this; // return reference to invoking object
}
最佳答案
两个不同的对象可以彼此相等,但这并不意味着它们相同。
考虑一下
#include <iostream>
#include <iomanip>
int main()
{
int x = 0;
int y = 0;
std::cout << "x == y is " << std::boolalpha << ( x == y ) << '\n';
std::cout << "&x == &y is " << std::boolalpha << ( &x == &y ) << '\n';
}
程序输出为
x == y is true
&x == &y is false
因此,需要此检查
this == &s
来确定此处是否存在自我分配。
关于c++ - 为什么不能设置* this ==类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61599681/