【问题标题】:Unhandled exception operator overloading未处理的异常运算符重载
【发布时间】: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

标签: c++ class templates


【解决方案1】:

你的函数递归调用自己,没有条件退出:

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

似乎有效。

如果您的警告级别足够高,您会看到关于此的警告:

Warning 1 警告 C4717: 'calc::operator+=' : 在所有控制路径上递归,函数会导致运行时堆栈溢出

话虽如此,您的代码还有一些其他问题,例如 int a 应该是 one a

friend const calc operator + (const calc& our, const calc& other);

应该只是普通的+ 操作员而不是朋友。

【讨论】:

  • 其实最好实现operator +=中的低级代码,而不是operator +,让operator +调用operator +=
  • @PaulMcKenzie 很酷,很高兴知道。我将进行编辑以更清楚地说明这一点。
猜你喜欢
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
相关资源
最近更新 更多