c++ 运算符重载
测试运算符重载。
头文件MyVec.h:
#pragma once
#include <iostream>using namespace std;// 我的二维向量,测试运算符重载
class MyVec
{
private:int x, y;public:MyVec(int x = 0, int y = 0);// 成员函数重载+MyVec operator+(const MyVec& rhs);// 成员函数重载-MyVec operator-(const MyVec& rhs);// 友元函数重载<<friend ostream& operator<<(ostream& os, const MyVec& v);// 成员函数重载[]int& operator[](int index);
};ostream& operator<<(ostream& os, const MyVec& v); // 上面那个友元函数的声明。不能缺少,不然外部不知道这个函数
源文件MyVec.cpp:
#include "MyVec.h"
#include <stdexcept>MyVec::MyVec(int x, int y) : x(x), y(y)
{
}MyVec MyVec::operator+(const MyVec& rhs)
{return MyVec(x + rhs.x, y + rhs.y);
}MyVec MyVec::operator-(const MyVec& rhs)
{return MyVec(x - rhs.x, y - rhs.y);
}ostream& operator<<(ostream& os, const MyVec& v)
{os << "(" << v.x << ", " << v.y << ")";return os;
}int& MyVec::operator[](int index)
{if (index == 0) return x;if (index == 1) return y;throw out_of_range("Index out of bounds");
}
测试代码:
#include "MyVec.h"void testYunsuanfuChongZai() {MyVec v1(1,2);MyVec v2(4); // 第二个参数有默认值0,可以不传MyVec v3 = v1 + v2;cout << v3 << endl;cout << "v3.x: " << v3[0] << ", v3.y: " << v3[1] << endl;
}
打印:
ok