C++操作符重载(operator)

发布时间 2023-08-23 17:33:35作者: 魔法少女小胖

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一般都作为对操作符重载使用