1、运算符的重载
运算符的重载有两种形式,第一种是在类里面完成重载,作为成员函数,第二种是在外面,作为友函数。
某一类的友函数是可以访问该类所有成员变量和成员函数的非成员函数。在类的.h文件中可以规定哪些函数时该类的友函数。
下面是友元函数的示例。
class n
{
public:
n(int a, int b);
n();
friend void ...
friend void ...
private:int a; int b;
}
接着我们以复数为例演示如何成员函数重载运算符:
1、+的重载:
//这是complex.h 文件
class complex//注意这里没有冒号
{
public:
complex(int real, int img);
complex();//构造函数不需要声明返回类型
void get();
complex operator+(complex c); //这一步重点讲一下,
//二元运算符的operator重载函数只有一个参变量,到时候实现的时候就该用这个参量加自己;
private:
int real;
int img;
};
//这是.h的实现文件
#include <complex.h>
#include <iostream>
using namespace std;
void complex::get()//先说类型再说类
{
cout << this->real << "+" << "i * "<<this->img << endl;
};
complex::complex(int real, int img)
{
this->real = real;
this->img = img;
};
complex::complex()
{
this->real = 0;
this->img = 0;
};
complex complex::operator+(complex c)
{
complex b;
b.img = this->img + c.img;
b.real = this->real + c.real;
return b;
};
//主函数
#include <complex.h>
#include <iostream>
using namespace std;
int main()
{
complex s1(1, 2);
complex s2(2, 3);
s1 = s1 + s2;
s1.get();
return 0;
}
加减都是一样的,这里再写一下乘除
其实只需要按照复数的乘除规则再修改一下就行了
我直接把所有代码放在一块儿
#include <complex.h>
#include <iostream>
using namespace std;
int main()
{
complex s1(1, 2);
complex s2(2, 3);
s1 = s1 * s2;
s1.get();
return 0;
}
class complex
{
public:
complex(int real, int img);
complex();
void get();
complex operator*(complex c);
private:
int real;
int img;
};
#include <complex.h>
#include <iostream>
using namespace std;
void complex::get()
{
cout << this->real << "+" << "i * "<<this->img << endl;
};
complex::complex(int real, int img)
{
this->real = real;
this->img = img;
};
complex::complex()
{
this->real = 0;
this->img = 0;
};
complex complex::operator*(complex c)
{
complex b;
b.img = this->real * c.img + this->img * c.real ;
b.real = this->real*c.real - this->img * c.img;
return b;
};
``