编写一个复数类,分别利用成员函数和友元函数实现两个复数的加法和减法运算。

个人实现代码:

class Complex {
public:
	Complex(int h,int m):A(h),B(m){}
	Complex()//创建构造函数
	{

	}
	int getA()//成员函数得出值
	{
		return A;
	}
	int getB()
	{
		return B;
	}
	Complex increase(Complex c)//成员函数定义
	{
		c.A = A + c.A;
		c.B = B + c.B;
		return c;
	}
	Complex decrease(Complex c)//成员函数定义
	{
		c.A = A-c.A;
		c.B = B - c.B;
		return c;
	}
	friend Complex increase1(Complex& c1, Complex& c2);//友元函数求和
	friend Complex decrease1(Complex& c1, Complex& c2);//友元函数求差
private:
	int A;
	int B;

};
Complex increase1(Complex& c1, Complex& c2)
{
	Complex p;
	p.A = c1.A + c2.A;
	p.B = c1.B + c2.B;
	return p;
}
Complex decrease1(Complex& c1, Complex& c2)
{
	Complex p;
	p.A = c1.A -c2.A;
	p.B = c1.B - c2.B;
	return p;
}
int main()
{
	Complex c1(2,3);
	Complex c2(1,2);
	cout << "使用成员函数求和:" << c1.increase(c2).getA() << "i+" << c1.increase(c2).getB() << "j" << endl;
	cout << "使用友元函数求和:" << increase1(c1,c2).getA() << "i+" << increase1(c1, c2).getB() << "j" << endl;
	cout << "使用成员函数求差:" << c1.decrease(c2).getA() << "i+" << c1.decrease(c2).getB() << "j" << endl;
	cout << "使用友元函数求和:" << decrease1(c1, c2).getA() << "i+" << decrease1(c1, c2).getB() << "j" << endl;
}

运行图:

编写一个复数类,分别利用成员函数和友元函数实现两个复数的加法和减法运算。_第1张图片

实例代码:

class Complex {
public:
    Complex(double real = 0.0, double imag = 0.0) : m_real(real), m_imag(imag) {}//double型更精确
    // 成员函数实现加法运算
    Complex add(const Complex& other) const {
        return Complex(m_real + other.m_real, m_imag + other.m_imag);//可以直接返回带实部和虚部的复数
    }
    // 成员函数实现减法运算
    Complex subtract(const Complex& other) const {//采用引用,不拷贝,可以节省空间
        return Complex(m_real - other.m_real, m_imag - other.m_imag);
    }
    // 友元函数实现加法运算
    friend Complex operator+(const Complex& a, const Complex& b);
    // 友元函数实现减法运算
    friend Complex operator-(const Complex& a, const Complex& b);
    void print() const {
        std::cout << "(" << m_real << " + " << m_imag << "i)" << std::endl;
    }
private:
    double m_real;  // 实部
    double m_imag;  // 虚部
};
// 友元函数实现加法运算
Complex operator+(const Complex& a, const Complex& b) {
    return Complex(a.m_real + b.m_real, a.m_imag + b.m_imag);
}
// 友元函数实现减法运算
Complex operator-(const Complex& a, const Complex& b) {
    return Complex(a.m_real - b.m_real, a.m_imag - b.m_imag);
}
int main() {
    Complex c1(3.0, 2.0);
    Complex c2(1.0, 4.0);
    // 使用成员函数进行加法和减法运算
    Complex c3 = c1.add(c2);
    Complex c4 = c1.subtract(c2);
    c3.print(); // (4 + 6i)
    c4.print(); // (2 - 2i)
    // 使用友元函数进行加法和减法运算
    Complex c5 = operator+(c1, c2);
    Complex c6 = operator-(c1, c2);
    c5.print(); // (4 + 6i)
    c6.print(); // (2 - 2i)
    return 0;
}

运行效果:

编写一个复数类,分别利用成员函数和友元函数实现两个复数的加法和减法运算。_第2张图片

你可能感兴趣的:(java,开发语言)