【C++】运算符重载
加号运算符重载成员函数实现#include<iostream>using namespace std;class Person {public:int a;int b;Person(){}Person(int a, int b){this->a = a;this->b = b;}Person operator+(const Person& p){Person tem
·
加号运算符重载
成员函数实现
#include<iostream>
using namespace std;
class Person {
public:
int a;
int b;
Person(){}
Person(int a, int b)
{
this->a = a;
this->b = b;
}
Person operator+(const Person& p)
{
Person temp;
temp.a = this->a + p.a;
temp.b = this->b + p.b;
return temp;
}
//运算符重载 也可发生函数重载
Person operator+(int val)
{
Person temp;
temp.a = this->a + val;
temp.b = this->b + val;
return temp;
}
};
int main()
{
Person p1(10, 10);
Person p2(10, 10);
Person p3 = p1 + p2 + 20;//相当于(p1.operator+(p2)).operator(20)
cout << "p3.a=" << p3.a << " p3.b=" << p3.b<<endl;
}
全局函数实现
#include<iostream>
using namespace std;
class Person {
public:
int a;
int b;
Person(){}
Person(int a, int b)
{
this->a = a;
this->b = b;
}
};
Person operator+(const Person& p1, const Person& p2)
{
Person temp;
temp.a = p1.a + p2.a;
temp.b = p1.b + p2.b;
return temp;
}
//运算符重载 可以发生函数重载
Person operator+(const Person& p1,int val)
{
Person temp;
temp.a = p1.a + val;
temp.b = p1.b + val;
return temp;
}
int main()
{
Person p1(10, 10);
Person p2(10, 10);
Person p3 = p1 + p2 + 20;//相当于(p1.operator+(p2)).operator(20)
cout << "p3.a=" << p3.a << " p3.b=" << p3.b<<endl;
}
左移运算符重载
成员函数无法实现
class Person {
public:
int a;
int b;
Person(int a, int b)
{
this->a = a;
this->b = b;
}
//因为重载运算符为成员函数后,当调用该运算符时,左操作数必须是该类的实例。如果支持成员函数实现的话,输出流的语句写法就变成了obj<<cout,不是想要的效果;
ostream& operator<<(Person& p)
{
cout << "p.a=" << p.a << " p.b=" << p.b << endl;
//返回cout的引用out才能进行后续的<<的链式编程
return cout;
}
};
全局函数实现
#include<iostream>
using namespace std;
class Person {
public:
int a;
int b;
Person(int a, int b)
{
this->a = a;
this->b = b;
}
};
//ostream 对象只能有一个,所以只能使用cout的引用
ostream& operator<<(ostream& out,Person& p)
{
out << "p.a=" <<p.a<< " p.b=" <<p.b<< endl;
//返回cout的引用out才能进行后续的<<的链式编程
return out;
}
//取消<<号的链式编程
//void operator<<(ostream& out, Person& p)
//{
// out << "p.a=" << p.a << " p.b=" << p.b << endl;
//}
int main()
{
Person p(10, 20);
//cout << p;//取消链式编程后只支持一个<<号,使用链式编程会报错
cout << p<<"hello world!";
}
更多推荐
已为社区贡献1条内容
所有评论(0)