#include <iostream>
using namespace std;
class study
{
public:
int m_A;
int m_B;
//通过成员函数重载
public:
study operator+(study &p1)
{
study temp;
temp.m_A = this->m_A + p1.m_A;
temp.m_B = this->m_B + p1.m_B;
return temp;
}
};
//通过全局函数重载
study operator+(study& p5, study& p6)
{
study temp;
temp.m_A = p5.m_A + p6.m_A;
temp.m_B = p5.m_B + p6.m_B;
return temp;
}
void test01()
{
study p2;
p2.m_A = 10;
p2.m_B = 10;
study p3;
p3.m_A = 20;
p3.m_B = 20;
study p4;
p4 = p3 + p2;
cout << "p4.m_A =" << p4.m_A << endl;
cout << "p4.m_B =" << p4.m_B << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
成员函数重载与全局函数重载只需要一个就好,不能两个形式重载一个函数
本文探讨了C++中如何通过成员函数和全局函数两种方式实现运算符重载。示例代码展示了如何重载加法运算符,创建了一个名为study的类,并在test01函数中进行了实例化和运算,输出了运算结果。这有助于理解C++的运算符重载机制。
1274

被折叠的 条评论
为什么被折叠?



