C++ oop运算符重载未返回正确的值
以下代码退出执行 有什么想法吗 我认为t1不等于t2,所以我试着逐字节复制t1和t2。但这并不奏效C++ oop运算符重载未返回正确的值,c++,oop,operator-overloading,C++,Oop,Operator Overloading,以下代码退出执行 有什么想法吗 我认为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");
#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;
}
#包括
课堂测试{
int x;
公众:
test(){x=1;}
布尔运算符==(测试和温度);
};
布尔测试::运算符==(测试和温度){
如果(*this==temp){
printf(“1”);
返回true;
}
否则{
printf(“2”);
返回false;
}
}
void main(){
试验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;
}