cpp学习(4)

7 篇文章 0 订阅

1、运算符的重载
运算符的重载有两种形式,第一种是在类里面完成重载,作为成员函数,第二种是在外面,作为友函数。
某一类的友函数是可以访问该类所有成员变量和成员函数的非成员函数。在类的.h文件中可以规定哪些函数时该类的友函数。
下面是友元函数的示例。

class n
{
	publicn(int a, int b);
	n();
	friend void ...
	friend void ...
	privateint 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;
};

``
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值