C++操作符重载(operator)

c++操作符

例如-=+*/等,甚至包括,<<等都是操作符。c++特色之一就是给予完全重构和重载操作符(Java不可以,c#操作部分)。

例子入手

假设一个结构体,定义如下

struct Vector2
{
float x, y;
Vector2(float x, float y)
:x(x),y(y){}
}

现在有如下两个定义

Vector2 position(4.0f, 4.0f);
Vector2 speed(0.5f, 1.5f);

我想实现两个结构体相加(即x+x,y+y)如何实现?

Ⅰ 定义一个方法

我们可以定义一个方法。

Vector2 add(const Vector2& other)const
{
return Vector2(x + other.x, y + other.y);
}

Ⅱ 操作符重载

我想实现例如外部仅需position+speed就可以实现结构体相加,如何?
当然可以,操作如下

Vector2 add(const Vector2& other)const
{
return Vector2(x + other.x, y + other.y);
}
Vector2 operator+(const Vector2& other)const
{
add(other);
}

此时使用+完全合法

使用控制台打印结构体/类

依旧有两个方法,我们可以在结构体内部定义此方法。如果想在外部直接打印的话会出现如下结果。
std::cout << speed << std::endl
image
这是因为cout只能输出普通类型,这时就要对<<进行重载。
重载函数如下

std::ostream& operator<<(std::ostream& stream, const Vector2& other)
{
return stream << other.x << "," << other.y ;
}

ostream一般都作为对操作符重载使用

posted @   魔法少女小胖  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示