【发布时间】:2019-11-10 09:32:57
【问题描述】:
我正在编写一个使用复数类的程序。我想使用函数void Input(Complex z) 来读取复数的实部和虚部并将它们分配给复数 z(这是参数),但是我得到了错误 Uninitialized local variable used和警告“使用未初始化的内存”。
我应该改变什么?
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();
}
【问题讨论】:
-
在
Input,Complex z是按值传递的。Input函数在main中没有任何改变,因此numar1保持未初始化状态。而是通过引用传递。 -
我可以理解你提到的警告,但你到底在哪里得到错误?顺便说一句,C++ 中的函数默认将数据作为值传递。您应该将输入功能的定义更改为@OblivionreinstateOurMonica 在他/她的回答中建议的方式。
-
如果你愿意,我可以发布完整的代码作为答案
-
有什么理由不使用std::complex?