#include <iostream>
using namespace std;
class Point {
friend ostream &operator<<(ostream& , const Point&);
friend istream &operator>>(istream& ,Point&);
int m_x;
int m_y;
public:
Point(int x = 0, int y = 0) :m_x(x), m_y(y) {}
const Point operator+(const Point& p1) const {
return Point(this->m_x + p1.m_x, this->m_y + p1.m_y);
}
Point& operator+=(const Point& p1) {
this->m_x += p1.m_x;
this->m_y += p1.m_y;
return *this;
}
bool operator==(const Point& p1) const {
return (m_x == p1.m_x) && (m_y == p1.m_y);
}
const Point operator-() const {
return Point(-m_x, -m_y);
}
const Point operator++(int) {
Point p(*this);
this->m_x++;
this->m_y++;
return p;
}
Point& operator++() {
this->m_x++;
this->m_y++;
return *this;
}
};
ostream& operator<<(ostream& cout, const Point& p1) {
cout << "(" << p1.m_x << "," << p1.m_y << ")";
return cout;
}
istream& operator>>(istream& cin, Point& p1) {
cin >> p1.m_x;
cin >> p1.m_y;
return cin;
}
int main() {
Point p;
cin >> p;
cout << p;
return 0;
}
#include <iostream>
using namespace std;
class Person {
int m_age;
public:
Person(int age) :m_age(age) {}
Person& operator=(const Person& p) {
m_age = p.m_age;
return *this;
}
};
class Student :public Person {
int m_score;
public:
Student(int age, int score) :Person(age), m_score(score) {}
Student& operator=(const Student& p) {
this->Person::operator=(p);
m_score = p.m_score;
return *this;
}
};
int main() {
return 0;
}
#include <iostream>
using namespace std;
class Sum{
public:
int operator() (int a,int b) {
return a + b;
}
};
int main() {
Sum sum;
cout << sum.operator()(10,30) << endl;
cout << sum(30,40) << endl;
return 0;
}
注意
- 有些运算符不可以重载
成员对象访问运算符 .
域运算符 ::
三目运算符 ? :
sizeof
- 有些运算符只能重载为成员函数
赋值运算符 =
下标运算法 []
函数运算符 ()
指针访问成员 ->