未处理的异常操作符重载

Unhandled exception operator overloading

本文关键字:重载 操作符 异常 未处理      更新时间:2023-10-16

我正在练习操作符重载,并建立了一个简单的计算器。

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);

应该是一个普通的+操作符,而不是友元。