操作符重载的概念

2 篇文章 0 订阅
2 篇文章 0 订阅

复数相加示例一:

#include <stdio.h>

class Complex 
{

    int a;
    int b;
public:
	Complex (int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}
	
	int getA()
	{
		return a;
	}
	int getB()
	{
		return b;
	}
	
	friend Complex Add(const Complex& p1, const Complex& p2);
};

Complex Add(const Complex& p1, const Complex& p2)
{
	Complex ret;
	
	ret.a = p1.a + p1.a;//私有化
	ret.b = p1.b + p2.b;
	
	return ret;
}

int main()
{

    Complex c1 = {1, 2};
	Complex c2 = {3, 4};
    Complex c3 = Add(c1, c2);
    
	printf("c3.a = %d\t c3.b = %d\n", c3.getA(), c3.getB());
	
    return 0;
}
  • 通过operator关键字定义操作符
  • 本质函数重载
#include <stdio.h>

class Complex 
{

    int a;
    int b;
public:
	Complex (int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}
	
	int getA()
	{
		return a;
	}
	int getB()
	{
		return b;
	}
	
	friend Complex operator +(const Complex& p1, const Complex& p2);
};

Complex operator +(const Complex& p1, const Complex& p2)//操作符重载
{
	Complex ret;
	
	ret.a = p1.a + p1.a;//私有化
	ret.b = p1.b + p2.b;
	
	return ret;
}

int main()
{

    Complex c1 = {1, 2};
	Complex c2 = {3, 4};
    
	Complex c3 = c1 + c2;//===>//Complex c3 = operator +(c1, c2);
    
	printf("c3.a = %d\t c3.b = %d\n", c3.getA(), c3.getB());
	
    return 0;
}

  • 当全局函数实现操作符重载和成员函数实现操作符重载
  • 编译器有限采取成员函数实现操作符的重载
#include <stdio.h>

class Complex 
{

    int a;
    int b;
public:
	Complex (int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}
	
	int getA()
	{
		return a;
	}
	int getB()
	{
		return b;
	}
	
	Complex operator +(const Complex& p)//操作符重载
	{
		Complex ret;
		printf("Complex operator +(const Complex& p)\n");
		ret.a = this->a + p.a;//私有化
		ret.b = this->b + p.b;
		
		return ret;
	}
	
	
	friend Complex operator +(const Complex& p1, const Complex& p2);
};

Complex operator +(const Complex& p1, const Complex& p2)//操作符重载
{
	Complex ret;
	printf("Complex operator +(const Complex& p1, const Complex& p2)\n");
	ret.a = p1.a + p1.a;//私有化
	ret.b = p1.b + p2.b;
	
	return ret;
}

int main()
{

    Complex c1 = {1, 2};
	Complex c2 = {3, 4};
    
	//Complex c3 = c1.operator + (c2);//===>//Complex c3 = operator +(c1, c2);
	Complex c3 = c1 + c2;//c1.opetator + c2//右操作符为c2,左操作符为this
    
	printf("c3.a = %d\t c3.b = %d\n", c3.getA(), c3.getB());
	
    return 0;
}

小结

  • 操作符重载:通过函数扩展操作符的功能
  • operator关键字实现操作符重载关键字
  • 全局函数和成员函数都可以实现对操作符的重载
  • 操作符重载的顺序优先选择成员函数、全局函数、编译器系统函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值