类的统一对象作为参数

Unitialized object of a class as parameters

本文关键字:参数 对象      更新时间:2023-10-16

我正在编写一个程序,该程序使用一个用于复数的类。我想使用函数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();
}

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

void Input(Complex& z)

住在Godbolt上。