未处理的异常操作符重载
Unhandled exception operator overloading
我正在练习操作符重载,并建立了一个简单的计算器。
template <class one> class calc {
int a;
public:
calc() : a(0) {};
calc(const calc& other) : a(other.a) {}
void print() { cout << a; }
calc& operator += (const calc& other);
calc& operator += (const one& i);
calc& operator -= (const calc& other);
calc& operator -= (const one& i);
calc& operator *= (const calc& other);
calc& operator *= (const one& i);
calc& operator /= (const calc& other);
calc& operator /= (const one& i);
const calc& operator - () const;
friend const calc operator + (const calc& our, const calc& other);
friend const calc operator + (const one& i, const calc& other);
friend const calc operator + (const calc& our, const one& i);
};
但不幸的是,当我试图实现这个类时,它抛出了异常:
实用编程c++中0x010154C9的未处理异常0xC00000FD: Stack overflow(参数:0x00000001,
0 x00192f64)。
main
:
int main() {
calc <int> one;
one += 2;
one.print();
cin.get();
}
这个问题不仅出现在这里,也出现在其他操作符中:
template <class one>
calc<one>& calc <one> :: operator += (const one& i) {
*this += i;
return *this;
}
你能告诉我我做错了什么吗?
你的函数递归地调用自己,没有退出的条件:
template <class one>
calc<one>& calc <one> :: operator += (const one& i) {
*this += i;
// ^calls the function youre currently in.
return *this;
}
你需要调整你的+=
操作符来使用你已经定义的+
操作符,或者正如@PaulMcKenzie所说,在+=
中做实际的加法,让+
使用+=
。例如,
template <class one>
calc<one>& calc <one> :: operator += (const one& i) {
a += i;
return *this;
}
似乎有效。
如果您的警告级别足够高,您可以看到关于此的警告:
警告1警告C4717: 'calc::operator+=':在所有控制路径上递归,函数将导致运行时堆栈溢出
话虽如此,你的代码还有一些其他问题,比如int a
应该是one a
和
friend const calc operator + (const calc& our, const calc& other);
应该是一个普通的+
操作符,而不是友元。
相关文章:
- 重载操作符+:表达式必须是整型或无作用域枚举类型
- 重载操作符
- 如何重载操作符==外模板类使用友元函数
- 重载*操作符,使其在左右两边都工作
- 重载操作符<对于非随机迭代器
- 在c++中重载操作符的时间和原因
- 如何在c++中重载=操作符来通过引用进行复制
- 如何在c++中获取定义为友元的重载操作符的地址
- 使用重载操作符的文件操作表达式没有给出预期的结果
- 重载操作符()
- 重载操作符()并在类内使用
- 类中的重载操作符+
- 定时使用重载操作符
- c++带类的重载操作符
- 用列表容器重载[]操作符
- 重载操作符=
- 任何重载操作符()的静态检测
- 重载操作符以处理类对象
- 在使用另一个类的类中重载操作符==
- 派生类和基类中的重载操作符不同