栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++运算符重载(02)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++运算符重载(02)

 类内/类外重载
#include 

//类内重载
class InPoint
{
public:
	InPoint() {};
	InPoint(int x, int y) : x(x), y(y){};
	InPoint operator+(const InPoint& b) //运算符作为类的成员函数
	{
		InPoint ret;
		ret.x = this->x + b.x;
		ret.y = this->y + b.y;
		return ret;
	}
	int x;
	int y;
};

//类外重载
class OutPoint
{
public:
	OutPoint() {};
	OutPoint(int x, int y) : x(x), y(y) {};

	friend OutPoint operator+(OutPoint a, OutPoint b);

	int x;
	int y;
};

//类内重载
OutPoint operator+(OutPoint a, OutPoint b)
{
	OutPoint c;
	c.x = a.x + b.x;
	c.y = a.y + b.y;

	return c;
}

class Point3
{
public:
	Point3() {};
	Point3(int x) : x(x) {};

	Point3 operator+(int x);

	int x;
};

Point3 Point3::operator+(int x)
{
	Point3 dd;
	dd.x = this->x + x;

	return dd;
}

int main()
{
	InPoint a(2, 3), b(3, 4);
	InPoint c = a + b; //隐式调用(成员函数)
	InPoint d = a.operator+(b); //显式调用(成员函数)

	OutPoint e(3, 4), f(4, 5);
	OutPoint g = operator+(e, f);//显示调用(友元函数) 

	std::cout << c.x << "; " << c.y << std::endl;

	Point3 gg(13);
	Point3 ff = gg + 3;
	std::cout << "ff = " << ff.x << std::endl;

	return -1;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629511.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号