#include<iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex()
{
real = 0;
imag = 0;
}
Complex(int r, int i) :real(r), imag(i) {};
friend Complex operator+(Complex &c1, Complex &c2);
void display();
};
void Complex::display()
{
cout << "real=" << real << endl;
cout << "imag=" << imag << endl;
}
Complex operator+(Complex &c1, Complex &c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main()
{
Complex c1(3, 4);
Complex c2(5, 8);
Complex c3;
c3 = c1 + c2;
c3.display();
return 0;
}
定义一个复数类,用友元函数实现对双目运算符“ + ”的运算符重载, 使其适用于复数运算
于 2018-06-17 23:12:45 首次发布
本文介绍了一个简单的C++程序,该程序定义了一个复数类Complex,并使用了友元函数来实现两个复数对象的加法运算。通过这个例子展示了如何在类中声明成员变量,构造函数以及成员函数,并且演示了友元函数如何访问类的私有成员。
667





