【发布时间】:2015-05-20 19:46:01
【问题描述】:
我正在练习运算符重载,并构建了一个简单的计算器。
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);
};
但不幸的是,当我尝试实现该类时,它会抛出异常:
Proctical 编程 C++ 中 0x010154C9 处未处理的异常 重载1.exe:0xC00000FD:堆栈溢出(参数:0x00000001, 0x00192F64)。
这里是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;
}
能否请您提示我做错了什么?
【问题讨论】:
-
还有什么例外?你为什么要从
+=打电话给+=? -
是的,抱歉,我已经编辑了问题
-
那么实际的
+=工作在哪里完成?您所做的只是从+=递归调用+=。换句话说,我看不到任何代码可以进行实际添加。 -
不应该是
a += i吗?a也应该是one a;而不是int a