C++初学者:尝试将两个功能合并为一个
C++ beginner: Trying to incorporate two functions into one
addComplex() 函数旨在接受两个 Complex 对象并返回一个 Complex 对象。返回对象的实部和虚部应该是传递给 addComplex() 的两个对象的实部和虚部之和。当然,如您所见,我只能让它返回真实部分的总和。如何在函数中包含虚部?
这是我已经工作了将近 2 个小时的家庭作业,并且正在碰壁。感谢任何正确方向的帮助。
我的代码:
#include <iostream>
#include <cmath>
using namespace std;
// class declaration section
class Complex
{
// friends list
friend double addComplex(Complex&, Complex&);
private:
double real;
double imag;
public:
Complex(double = 0, double = 0); // constructor
void display();
};
// class implementation section
Complex::Complex(double rl, double im)
{
real = rl;
imag = im;
}
void Complex::display()
{
char sign = '+';
if(imag < 0) sign = '-';
cout << real << sign << abs(imag) << 'i';
return;
}
// friend implementations
double addComplex(Complex &a, Complex &b)
{
return (a.real + b.real);
}
int main()
{
Complex a(3.2, 5.6), b(1.1, -8.4);
double num;
cout << "The first complex number is ";
a.display();
cout << "nnThe second complex number is ";
b.display();
cout << "nnThe sum of these two complex numbers is ";
num = addComplex(a,b);
Complex c(num);
c.display();
cout << "nnThis is the end of the program.n";
return 0;
}
您需要返回一个复杂对象,而不是双精度。
就一些代码质量提示而言,您应该创建一个常量访问器,而不是使其成为友元函数。此外,引用应该是 const 的,因为您没有修改输入。using std
通常被认为是不好的做法,尽管在非头文件中还不错。
Complex addComplex(const Complex& a, const Complex& b)
{
return Complex(a.real + b.real, a.imag + b.imag);
}
Complex addComplex(Complex &a, Complex &b)
{
return Complex(a.real + b.real, a.imag + b.imag);
}
您可能还需要考虑使"addComplex"函数成为"+"运算符的重载。
addComplex
应该返回一个Complex
对象:
Complex addComplex(const Complex &a, const Complex &b)
{
/*Sum the real and imaginary parts, and use the constructor*/
return Complex(a.real + b.real, a.imag + b.imag);
}
我还制作了 parmaeters const
引用类型。这有助于程序稳定性,因为这意味着该函数无法修改a
和b
。
相关文章:
- 两个文件使用彼此的功能-如何解决
- 两个数字的对称配对功能
- 检查两个图是否为补码的功能
- 当我链接两个静态C++库时,我可以在两个主函数库中有两个主要功能吗?
- 当两个功能非常相似时,如何避免复制和粘贴?
- 如何使用 Turbo C++并行运行两个功能,一个用于键盘,一个用于鼠标?
- 维护/维持两个代码集的风险,一个用于 CPU,一个用于 GPU,需要执行非常相似的功能
- 如何比较C 中的两个字符串并使用默认功能
- 两个功能的过载分辨率采用参数包
- 调用两个功能(一个stdcall)的方法
- 两个功能并没有花时间我期望的,因为它们的复杂性很大,任何人都可以解释原因
- 为什么这两个功能不能超载
- C :两个功能,每个功能都采用枚举参数,签名匹配
- C ,以并行和协作的方式运行两个功能
- 如何使用两个功能在C++中绘制空心钻石
- 在C++中,是什么导致了这两个功能之间的差异
- 这两个功能能合二为一吗?
- 不需要两个功能+过载吗?
- 多线程两个功能使用openMP
- C++初学者:尝试将两个功能合并为一个