我想通过使用构造函数从用户获取值,而另一个值将在程序本身中。我尝试编写如下代码。但构造函数正在将所有值初始化为0,0(无参数)。怎么办?
#include<iostream>
using namespace std;
class complex
{
float x;
float y;
public :
complex() //no argument constructor
{
/* cout<<"Enter real = ";
cin>>x;
cout<<"Enter imaginary = ";
cin>>y;*/
}
complex(float real, float imag)
{
cout<<"Enter real = ";
cin>>x;
cout<<"Enter imaginary = ";
cin>>y;
x = real;
y = imag;
}
complex operator+(complex);
void display(void);
};
complex complex :: operator+(complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y+c.y;
return(temp);
}
void complex :: display(void)
{
cout<<x<<" +i"<<y<<"\n";
}
int main()
{
complex c1,c2(2.5,1.7),c3(0,0);
c3 = c1+c2;
c1.display();
c2.display();
c3.display();
system ("PAUSE");
// return 0;
}
答案 0 :(得分:1)
以下可能是你想要的。 我将您的复数类更改为仅使用一个具有默认参数的构造函数,如果您不提供任何参数,则默认为0。
在你的代码中,你的参数less函数什么都不做,默认只使用x和y的默认构造函数(在使用0的浮点数的情况下)。如上所述,您可以使用默认参数将其与参数化构造函数结合使用。
这清楚地表明,如果你没有为Complex构造函数提供值,你应该期望x和y为0.
我还添加了输入和输出流操作符,但这可能不是您的用途所必需的。
但它允许您使用cin >> c1;
,很明显您希望用户输入c1的值,而不是将该代码嵌入到默认构造函数中。
#include<iostream>
using namespace std;
class complex{
float x;
float y;
public :
// it seems like one constructor with default parameters
// should work for your case.
complex(float real = 0, float imag = 0):x(real),y(imag){}
complex operator+(complex);
friend ostream& operator << (ostream& outs, Complex C);
friend istream& operator << (istream& ins, Complex C);
};
ostream& operator << (ostream& outs, Complex C){
cout << C.x << " + i" << C.y;
return outs;
}
istream& operator << (istream& ins, Complex C){
if (ins == cin){
cout << "Enter real part" << endl;
ins >> C.x;
cout << "Enter imaginary part" << endl;
ins >> C.y;
} else {
ins >> C.x >> C.y;
}
return ins;
}
// your plus operator is fine.
int main(){
complex c1,c2(2.5,1.7),c3(0,0); //c1 will have x = 0, y = 0
c3 = c1+c2; // c3.x = 2.5, c3.y = 1.7
cout << c1 << endl; // displays 0 + i0
cout << c2 << endl; // displays 2.5 + i1.7
cout << c3 << endl; // displays 2.5 + i1.7
return 0;
}
输出:
0 + i0
2.5 + i1.7
2.5 + i1.7
如果这不是您对输出的期望,您会期待什么?
答案 1 :(得分:0)
我做了一些假设并相应修改了你的代码,假设是:
请记住以上内容,可以按如下方式修改代码:
#include<iostream>
using namespace std;
class complex
{
float x;
float y;
public :
complex() {}
complex(float real, float imag) { x=real; y=imag; } //constructor for creating x and y from values given in the code
complex(istream&);//constructor for creating values entered as input
complex operator+(complex);
void display(void);
};
//definition for constructor for taking user input
complex::complex(istream& in)
{
cout<<"Enter real = ";
in>>x;
cout<<"Enter imaginary = ";
in>>y;
}
complex complex :: operator+(const complex& c) const
{
complex temp;
temp.x = x + c.x;
temp.y = y+c.y;
return(temp);
}
void complex :: display(void)
{
cout<<x<<" +i"<<y<<"\n";
}
int main()
{
complex c1(cin),c2(2.5,1.7),c3;
//note the changes, c1 is made from user input, c2 from constructor and c3 using default constructor
c3 = c1+c2;
c1.display();
c2.display();
c3.display();
}
记下我在评论专栏中指出的修改