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

理解:相同函数名的函数或者同一运算符,在不同场合有不同的功能。编译器通过不同的接口,判断执行哪一种功能(重载决策)。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:

};

 

编译运行