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

oop operator overloading not returning proper value

本文关键字:返回 运算符 重载 oop      更新时间:2023-10-16

以下代码退出执行。

有什么想法吗?

我认为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){ // &

你必须决定阶级平等意味着什么。上面的行假设一个类等于它自己。但是,例如,如果将类定义为相等(如果它们具有相同的x值(,则可以编写

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