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

  • c++支持运算符重载,允许在程序中定义或更改运算符的行为。
  • #include
    #include
    
    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
    #include
    
    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;
    }

你可能感兴趣的:(c++,学习,笔记)