What is operator overloading?
Operator overloading concepts: the existing operators are redefined, giving it another function, to accommodate different data types
For individuals learn feeling here is, more than a way to customize the way that it calculates, to automatically effect a corresponding operator through the operation similar syntactic sugar +
The + operator overloading:
Action: implement two types of custom data adding operation
In which the + operator overloading, we can be defined in two ways, one is a member function to perform , there is a global function is achieved
The same call, there are two methods, the following code is reflected
Sample code:
#include<iostream>
#include<string>
using namespace std;
class Person{
public:
//成员函数实现 + 号运算符重载
//Person operator+(Person &p1) {
// Person temp;
// temp.age = this->age + p1.age;
// return temp;
//}
public:
int age;
};
//全局函数 实现+号运算符重载
Person operator+(Person &p1, int val) {
Person temp;
temp.age = p1.age + val;
return temp;
}
int main() {
Person p1;
p1.age = 20;
//Person p2 = p1.operator+(p1); //调用方式有两种,这是第一种
Person p2 = p1 + 10;//这是第二种调用方式
cout << p2.age << endl;
system("pause");
return 0;
}
Summary 1: For the built-in data type of an expression is unlikely to change operator
Summary 2: Do not abuse operator overloading