class Complex
{
public:
Complex(float = 0.0, float = 0.0); //default constructor that uses default arg. in case no init. are in main
void getComplex(); //get real and imaginary numbers from keyboard
void sum(Complex, Complex); //method to add two complex numbers together
void diff(Complex, Complex); //method to find the difference of two complex numbers
void prod(Complex, Complex); //method to find the product of two complex numbers
void square(Complex, Complex); //method to change each complex number to its square
void printComplex(); //print sum, diff, prod, square and "a+bi" form
private:
float real; //float data member for real number (to be entered in by user)
float imaginary; //float data member for imaginary number (to be entered in by user)
};
void Complex::getComplex()
{
cout << "Enter real number: ";
cin >> real;
cout << "Enter imaginary number: ";
cin >> imaginary;
}
void Complex::sum(Complex, Complex)
{
float sum = 0.0;
sum = real + imaginary;
}
int main()
{
Complex c;
c.getComplex();
c.sum(Complex, Complex);
c.diff(Complex, Complex);
c.prod(Complex, Complex);
c.square(Complex, Complex);
c.printComplex();
return 0;
}
我在主内部c.sum(Complex, Complex);
下面收到错误(以及c.diff
,c.prod
和c.square
行。错误是:
type name Complex is not allowed
和too few arguments in function call
根本不允许我使用重载操作符来完成此任务。我该怎么做才能解决此问题?代码已缩写为显示相关部分。再次感谢。
答案 0 :(得分:0)
假设:你的类的sum,diff等方法不应该返回任何结果或者修改传递给它们的类实例,而只是通过std显示操作的结果::法院。
请至少阅读http://www.cplusplus.com/doc/tutorial/functions/以了解如何将值传递给函数(或在本例中使用方法,请参阅http://www.cplusplus.com/doc/tutorial/classes/)
虽然只能通过编写参数类型来声明方法,但您必须在定义中指定标识符: `
void Complex::sum(Complex c1, Complex c2)
{
}
然后您可以访问c1和c2的成员,例如c1.imaginary
传递c1和c2的更有效方法是使用&#34; const引用&#34; const Complex& c1
。然后不会制作对象的副本。
实际上,方法sum,diff,prod可以成为静态方法,因为它们对主对象中的复杂对象c没有影响(遵循我的假设)。所以它应该是
Complex::sum(c1, c2);
如果我的假设是错误的,并且c.sum()
实际上会对c产生影响,我不明白为什么你需要这个方法的两个参数。你可以把c1添加到c。但是,该方法应该被称为Add
。或者您必须将总和作为新对象返回,但该方法被声明为无效。