运算符重载
2025/8/4大约 2 分钟
运算符重载
为什么需要使用运算符重载?
使用成员函数重载运算符
牛类
/*牛*/
class Cow
{
public:
Cow(int weight);
~ Cow();
// 运算符重载
int operator+(const Goat& goat);
int getWeight() const;
private:
int weight; // 体重
};
Cow:: Cow(int weight)
{
this->weight = weight;
}
Cow::~ Cow()
{
}
int Cow::operator+(const Goat& goat)
{
return weight + goat.getWeight();
}
int Cow::getWeight() const
{
return this->weight;
}
羊
class Goat
{
public:
Goat(int weight);
~Goat();
int getWeight() const;
private:
int weight; // 体重
};
Goat::Goat(int weight)
{
this->weight = weight;
}
Goat::~Goat()
{
}
int Goat::getWeight() const
{
return weight;
}
测试代码
int main () {
Cow cow(600);
Goat goat(100);
int total = cow + goat;
cout << "牛:" << cow.getWeight() << ", 羊:" << goat.getWeight() << ", 一共:" << total << endl;
return 0;
}
输出:
牛:600, 羊:100, 一共:700
D:\code\cpp\ConsoleApplication1\Release\ConsoleApplication1.exe (进程 1180)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
使用友元函数重载运算符
在类外定义一个函数
int operator+(Cow& cow, Cow& cow2) {
return cow.weight + cow2.weight;
}

可以看到默认是不允许访问私有属性的,在Cow类中添加一个友元函数定义
/*牛*/
class Cow
{
public:
Cow(int weight);
~ Cow();
// 原来的自定义运算符函数注释了。
// 运算符重载
//int operator+(const Goat& goat);
int getWeight() const;
// 友元函数
friend int operator+(Cow& cow, Cow& cow2);
private:
int weight; // 体重
};

可以看到,现在不报错了。

// 友元重载运算符函数定义测试
Cow cow1(600);
Cow cow2(700);
int total = cow1 + cow2;
cout << "牛1:" << cow1.getWeight() << ", 羊2:" << cow2.getWeight() << ", 一共:" << total << endl;
- 需要注意的是,这样把所有的代码都卸载一个类中的话,是有顺序要求的,c++ 和Java 、python不一样,他的函数定义位置是有要求的,Java、Python 没这个要求。
- 建议还是分开写,这么写有点乱。
运算符重载的禁区和规则
至少有一个不是标准对象,即必须有一个是用户自定义的对象
禁止对标准对象进行运算符重载
完整代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Goat
{
public:
Goat(int weight);
~Goat();
int getWeight() const;
private:
int weight; // 体重
};
Goat::Goat(int weight)
{
this->weight = weight;
}
Goat::~Goat()
{
}
int Goat::getWeight() const
{
return weight;
}
class Pork
{
public:
Pork(int weight);
~Pork();
private:
int weight; // 体重
};
Pork::Pork(int weight)
{
this->weight = weight;
}
Pork::~Pork()
{
}
/*牛*/
class Cow
{
public:
Cow(int weight);
~ Cow();
// 运算符重载
//int operator+(const Goat& goat);
int getWeight() const;
// 友元函数
friend int operator+(Cow& cow, Cow& cow2);
private:
int weight; // 体重
};
Cow:: Cow(int weight)
{
this->weight = weight;
}
Cow::~ Cow()
{
}
//int Cow::operator+(const Goat& goat)
//{
// return weight + goat.getWeight();
//}
int Cow::getWeight() const
{
return this->weight;
}
int operator+(Cow& cow, Cow& cow2) {
int total = cow.weight + cow2.weight;
return total;
}
int main () {
// 内部函数重载运算符定义测试
//Cow cow(600);
//Goat goat(100);
//int total = cow + goat;
//cout << "牛:" << cow.getWeight() << ", 羊:" << goat.getWeight() << ", 一共:" << total << endl;
// 友元重载运算符函数定义测试
Cow cow1(600);
Cow cow2(700);
int total = cow1 + cow2;
cout << "牛1:" << cow1.getWeight() << ", 羊2:" << cow2.getWeight() << ", 一共:" << total << endl;
return 0;
}