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

标签 c++ class operator-overloading definition assignment-operator

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

相关文章:

javascript - C++ 库与 Ionic 框架的集成

c++ - 为列表迭代器的映射定义 < 运算符

java - 错误 : Could not find or load main class org. newdawn.slick.tests.AlphaMapTest

c++ - 返回其自身类型的模板类方法的正确签名

generics - Swift 泛型运算符

c++ - < 运算符在不应该返回 true 时返回 true

c++ - 如何在boost共享内存中直接写入opencv cv::Mat图像

c++ - C++ 中静态指针类成员链接期间的 undefined reference

.net - 在 F# 中重载 "="和 "<>"

c++ - 链接 operator<< 和 operator++ 的问题