如何在C++中构建一个复数类,以便将它们相加?[已关闭]

5kgi1eie  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(88)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
昨天关门了。
Improve this question
我对C中的类还是个新手。我用C写了一段代码,用Xcode输入/输出复数之和,不知怎么的,输出不是它应该的样子。
这是我的代码:

#include <iostream>
using namespace std;

class Complex {
private:
double re,im;
public:
Complex (double Re=0, double Im=0): re(Re), im(Im) { }

friend Complex operator+(Complex z1, Complex z2){
    return Complex(z1.re+z2.re, z1.im+z2.im); }

friend ostream& operator<<(ostream& stream, Complex z){
    stream << "(" << z.re << "," << z.im << ")" ;
    return stream; }

friend istream& operator>>(istream& stream, Complex& z){
    char c1,c2,c3;
    double x,y;
    stream >> c1 >> x >> c2 >> y >> c3;
    if (c1!='(' || c2!=',' || c3!=')')
        stream.setstate(ios::failbit);
    z = Complex(x,y);
    return stream; }
};

int main() {
    Complex z1,z2;
    cout << "z1 z2: "; cin >> z1 >> z2;
    cout << "z1+z2 = " << z1+z2 << endl;
return 0; }

有人能告诉我我的错误在哪里,以及如何解决/改进它吗?
Xcode首先说"Build successed",我用不同的输入测试过很多次,但输出从来都不正确。
例如

z1 = (1,2) z2 = (3,4)  output is (2,4)
z1 = (5,6) z2 = (7,8)  output is (10,12)

我的意见:

z1 z2:(1,2) (3,4)
z1+z2 = (2,4)
Program ended with exit code: 0

对于这个输入,我有:

z1 z2:(12,3)

z1+z2 = (24,6)
Program ended with exit code: 0

先谢了!

l0oc07j2

l0oc07j21#

你的程序没问题,我想你的错误是输入错误造成的。
输入分析函数未正确处理错误。

friend istream& operator>>(istream& stream, Complex& z){
    char c1,c2,c3;
    double x,y;                          // x, y are uninitialized.
    stream >> c1 >> x >> c2 >> y >> c3;
    if (c1!='(' || c2!=',' || c3!=')')
        stream.setstate(ios::failbit);   // What does this do for you?  
                                         // On error, you return garbage.
                                         // Maybe you should throw instead.

    z = Complex(x,y);                    // on error, x, y are still uninitialized.
    return stream; }
};

试试这个:

#include <exception>

// ...

friend istream& operator>>(istream& stream, Complex& z){
    char c1,c2,c3;
    double x,y;
    stream >> c1 >> x >> c2 >> y >> c3;
    if (c1!='(' || c2!=',' || c3!=')')
        throw std::runtime_error{"Could not read complex from input stream"};
    z = Complex(x,y);
    return stream; }
};

相关问题