欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > c++ 运算符重载

c++ 运算符重载

2025/9/19 15:37:36 来源:https://blog.csdn.net/u012116089/article/details/148030597  浏览:    关键词: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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com