类的统一对象作为参数

我正在编写一个使用类处理复数的程序。我想使用函数void Input(Complex z)来读取复数的实部和虚部,并将它们分配给复数z(这是参数),但是出现错误使用未初始化的局部变量和警告“正在使用未初始化的内存”。

我应该改变什么?

class Complex
{

    float x,y;
public:
    float modul() { return sqrt(x * x + y * y); };
    void setcomplex(float a,float b) { x = a; y = b; };
    void getcomplex() { cout << "(" << x << "," << y << ")"; };
    float getreal() { return x; };
    float getimaginar() { return y; };
};

Complex suma(Complex a,Complex b)
{
    Complex c;
    c.setcomplex( a.getreal() + b.getreal(),a.getimaginar() + b.getimaginar() );
    return c;

}

void Input(Complex z)
{
    float a,b;
    cout << endl << "Real part:"; cin >> a;
    cout << endl << "Imaginary part:"; cin >> b;
    z.setcomplex(a,b);
}

int main()
{
    Complex numar1;
    Input( numar1);
    numar1.getcomplex();
}
wang0707 回答:类的统一对象作为参数

如果要更改传递给函数的对象的状态并对新状态感兴趣,则需要通过引用该函数来传递它:

void Input(Complex& z)

Godbolt上直播。

本文链接:https://www.f2er.com/3129797.html

大家都在问