gpt4 book ai didi

c++ - 为什么不能设置* this ==类对象

转载 作者:行者123 更新时间:2023-12-02 09:49:24 24 4
gpt4 key购买 nike

我正在查看重载运算符=。
为什么我可以设置'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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com