【C++学习笔记】Step3 重载函数与重载运算符

目的:掌握重载的概念,程序实现重载函数和重载运算符的功能

理解:相同函数名的函数或者同一运算符,在不同场合有不同的功能。编译器通过不同的接口,判断执行哪一种功能(重载决策)。1.实现接口;2.根据接口实现对应功能。

码云:https://gitee.com/hinzer/my-notes-of-C_plus

 

思维导图

 

代码 main.cpp

#include "iostream"

using namespace std;

//测试函数重载
class Hello
{
public:
	Hello()
	{

	}

	void sayHello()
	{//接口1
		cout << "hello hinzer" << endl;

	}

	void sayHello(string name)
	{//接口2
		string str = "hello ";
		str += name;	//拼接字符串

		cout << str << endl;

	}
private:

};

class Point
{
public:
	Point(int x,int y)
	{//通过this指针 访问对象属性
		this->x = x;
		this->y = y;

	}
	int getX()
	{
		return this->x;
	}
	int getY()
	{
		return this->y;
	}
	void add(Point p)
	{
		add(p.getX(),p.getY());
	}
	void add(int x,int y)
	{//将x、y分别累加到对象的x和y
		this->x += x;
		this->y += y;
	}
	void operator+=(Point p)
	{//将Point p作为参数,实现运算符重载
		add(p);
	}
private:
	//定义坐标
	int x,y;

};

int main(int argc, char const *argv[])
{

	Hello *p = new Hello();
	p->sayHello();	//默认方法

	string str = "wangjian";
	p->sayHello(str);	//实现函数重载

	delete p;

	Point a(10,10);
	a += Point(13,15);	//因为Point(13,13)是Point类的对象,所以对 += 进行重载  与 a.operator+=(Point p) 等价

	cout << "x:" << a.getX() << endl;
	cout << "y:" << a.getY() << endl;

	return 0;
}

 

编译运行

 

补充·伪函数

在类A中实现'()'运算符的重载,使类像函数一样使用。

 

//测试函数重载
class Hello
{
public:
	Hello()
	{

	}

	void sayHello()
	{//接口1
		cout << "hello hinzer" << endl;

	}

	void sayHello(string name)
	{//接口2
		string str = "hello ";
		str += name;	//拼接字符串

		cout << str << endl;

	}

	void operator()()
	{//实现对'()'的重载
		cout << "hello __wangjian__" << endl;

	}
private:

};

 

编译运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hinzer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值