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){ // &
你必须决定阶级平等意味着什么。上面的行假设一个类等于它自己。但是,例如,如果将类定义为相等(如果它们具有相同的x
值(,则可以编写
bool test::operator==(test &temp){
if (this->x == temp.x){
printf("1");
return true;
}
else{
printf("2");
return false;
}
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用赋值运算符重载从类中返回jobject
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 重载更少,则运算符返回相反的布尔值
- 是否所有C++运算符都返回一些内容
- 使用重载 [] 运算符返回 std::map() 的可赋值
- 三元运算符在返回语句中给出意外的结果
- 为什么重载运算符可以返回其返回类型以外的其他内容?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 返回 bool 作为 CPP 中 bool 运算符 [] 中的值
- 运算符重载C++类中的引用返回
- 如何使用运算符+重载函数正确返回对象?
- 我的运算符重载没有在我的 int main 中返回?
- 在C++中,运算符 sizeof 返回什么数据类型?
- 为什么我的超载"+"运算符返回的总额错误?
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- 如何在C++中正确地返回运算符(*,/,-,+)
- C++ 函数返回 &&& 运算符
- 返回运算符类型=-引用或值