一.+号运算符重载
//
// main.c
// cdemo
//
// Created by liyongkai on 2021/6/6.
//
#include <iostream>
using namespace std;
class Person{
public:
int a;
int b;
Person(){};
Person(int a, int b):a(a), b(b) {
};
//+号运算符重载
Person operator+(Person &p) {
Person temp;
temp.a = this->a + p.a;
temp.b = this->b + p.b;
return temp;
};
};
int main(int argc, const char * argv[]) {
Person p1 = Person(1,2);
Person p2(10, 10);
Person p3 = p1 + p2;
cout << "a:" << p3.a << " " << "b:" << p3.b << endl;
//a:11 b:12
return 0;
}
二.<<号运算符重载
//
// main.c
// cdemo
//
// Created by liyongkai on 2021/6/6.
//
#include <iostream>
using namespace std;
class Person{
public:
int a;
int b;
};
ostream& operator<<(ostream &cout, Person &p) {
cout << "a:" << p.a;
return cout;
}
int main(int argc, const char * argv[]) {
Person p1;
p1.a = 10;
cout << p1 << endl;//a:10
return 0;
}
三.指针运算符重载(智能指针)
网友评论