C++学习笔记(二十三):c++ 运算符重载

2024-01-07 18:25:35
  • c++支持运算符重载,允许在程序中定义或更改运算符的行为。
  • #include<iostream>
    #include<string>
    
    struct Vector2 
    {
    	float x, y;
    	Vector2()
    	{}
    	Vector2(float x, float y)
    		:x(x), y(y)
    	{}
    	//返回值类型Vector2  operator (参数)
    	Vector2 operator+ (Vector2 v)
    	{
    		Vector2 temp;
    		temp.x = x + v.x;
    		temp.y = y + v.y;
    		return temp;
    	}
    };
    
    int main()
    {
    	Vector2 v1(1.0, 4.3);
    	Vector2 v2(7.3, 9.8);
    	//实现两个Vector类对象的属性相加
    	//重载运算符+
    	Vector2 v3 = v1 + v2;
    	std::cout << v3.x << std::endl;
    	std::cin.get();
    	return 0;
    }
  • #include<iostream>
    #include<string>
    
    struct Vector2 
    {
    	float x, y;
    	Vector2()
    	{}
    	Vector2(float x, float y)
    		:x(x), y(y)
    	{}
    	//返回值类型Vector2  operator (参数)
    	Vector2 operator+ (Vector2 v)
    	{
    		Vector2 temp;
    		temp.x = x + v.x;
    		temp.y = y + v.y;
    		return temp;
    	}
    };
    //重写 << 操作符
    std::ostream& operator<< (std::ostream& stream, const Vector2& other)
    {
    	stream << other.x << " " << other.y;
    	return stream;
    }
    int main()
    {
    	Vector2 v1(1.0, 4.3);
    	Vector2 v2(7.3, 9.8);
    	//实现两个Vector类对象的属性相加
    	//重载运算符+
    	Vector2 v3 = v1 + v2;
    	std::cout << v3 << std::endl;
    	std::cin.get();
    	return 0;
    }

文章来源:https://blog.csdn.net/qq_16701727/article/details/135362000
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。