运算符重载、友元

11 阅读1分钟
#include<iostream>
struct Vertex {
	float x, y;

	Vertex add(const Vertex& other) const {
		return Vertex(x + other.x, y + other.y);//返回构建的临时对象
	}
	Vertex operator+(const Vertex& other)const {//运算符+重载
		return Vertex(x + other.x, y + other.y);
	}
	Vertex Multiply(const Vertex& other)const {
		return Vertex(x * other.x, y * other.y);
	}
	Vertex operator*(const Vertex& other)const {//运算符*重载
		return Vertex(x * other.x, y * other.y);
	}
        bool operator==(const Vertex& other)const {//运算符==重载,判断两个向量是否相同
            return (x == other.x) && (y == other.y);
	}
        
	//friend std::ostream& operator<<(std::ostream& stream, const Vertex& vertex);
	//一般可能需要声明为友元函数,以便访问类中private成员,不过此处由于默认public所以不用做此声明
};
std::ostream& operator<<(std::ostream& stream, const Vertex& vertex) {
	stream << vertex.x << ", " << vertex.y;
	return stream;
}//此为标准输出流重载的模板,灵活改变 "const Vertex& vertex"
int main() {
	Vertex speed(0.5f, 0.5f);
	Vertex position( 1.f,-1.f );
	Vertex powerup( 3.f,3.f );
	Vertex result1 = position.add(speed.Multiply(powerup));
	std::cout << result1 << std::endl;
	Vertex result2 = position + speed * powerup;
	std::cout << result2 << std::endl;
        std::cout << (result1 == result2) << std::endl;
}