oop 运算符重载不返回正确的值

oop operator overloading not returning proper value

以下代码退出执行。

一些想法?

我在想t1不等于t2,所以我试着逐字节复制t1和t2。但这并没有奏效。

#include<stdio.h>
class test{
    int x;
public:
    test(){ x=1; }
    bool operator==(test &temp);

};

bool test::operator==(test &temp){
    if(*this==temp){
        printf("1");
        return true;
    }
    else{ 
        printf("2"); 
        return false;
    }


}
void main(){
    test t1, t2;
    t1==t2;

}

这一行

if (*this == temp){

再次调用 operator==,所以我们以堆栈溢出结束。

也许你的意思是

if (this == &temp){ // &

你必须决定 class 相等是什么意思。上面的行假设 class 等于它自己。但是,例如,如果您将 classes 定义为相等,如果它们具有相同的 x 值,您可以写

bool test::operator==(test &temp){
if (this->x == temp.x){
    printf("1");
    return true;
}
else{
    printf("2");
    return false;
}