运算符重载中的答案不正确

时间:2012-08-15 21:02:08

标签: c++

我刚刚学习了运算符重载,我想尝试创建一个代表复数的对象。我写了以下内容:

#include <iostream>

using namespace std;

class complexNumber
{
    public:
        double re, im;
        complexNumber(){}
        complexNumber(double a, double b)
        {
            re = a;
            im = b;
        }
        complexNumber operator+ (complexNumber b)
        {
            complexNumber c;
            c.re = re + b.re;
            c.im = im + b.im;
        }
        complexNumber operator- (complexNumber b)
        {
            complexNumber c;
            c.re = re - b.re;
            c.im = im - b.im;
        }
};

int main()
{
    complexNumber a(1,2);
    complexNumber b(4,6);
    complexNumber c;
    complexNumber d;

    c = a + b;
    d = a - b;

    cout << c.re << " + " << c.im << "i" << endl;
    cout << d.re << " + " << d.im << "i" << endl;
}

我得到了结果:

2.44156e + 253 + 6.95225e-308i

2.44156e + 253 + 6.95225e-308i

我在这里出错的任何想法。 提前谢谢。

1 个答案:

答案 0 :(得分:5)

您需要从函数中返回一个值。你的编译器没有警告你这个吗?