我正在检查重载运算符=。 为什么我可以设置'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
}
答案 0 :(得分:2)
比较2个指针与比较这些指针的值不是同一件事。例如
int *a, *b;
if(a == b)
if (*a == *b) // not the same
当然,如果2个指针相同,则它们指向相同的值,但反之则不成立。
在这种情况下,检查*this == st
是否可以编译(假设operator==
是为StringBad
定义的),但这与检查this == &st
是否相同。
答案 1 :(得分:2)
两个不同的对象可以彼此相等,但这并不意味着它们是相同的。
例如考虑
#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
,以确定此处是否存在自我分配。
答案 2 :(得分:0)
为什么我可以设置
this == &st
但不能设置*this == st
?
我想你是说,为什么我可以使用this == &st
但不能使用*this == st
?
暂时忽略一下,答案是可以的,但这不一定总是正确的做法。这可能适合您的情况。在这种情况下,您当然应该使用它。当然,这意味着您需要首先为您的类实现operator==
。
在此示例中,您不应该使用*this == st
来使分配不起作用。
假设您有一个用值和单位捕获物理量的类,并假设您拥有:
对象a
,代表1“ m”。
对象b
,代表100“ cm”。
将a
与b
进行比较时,您应该返回true
。但是,当您将a
分配给b
或反之亦然时,IMO应该继续进行分配。