重载运算符
重载一元负运算符
Counter operator-() const {
return Counter(-count);
}
bool operator!() const {
return count == 0;
}
int getValue() const {
return count;
}
};
二元运算符重载(例如: + , - , * , / , == , < ):
class Point {
private:
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
Point operator+(const Point& rhs) const {
return Point(x + rhs.x, y + rhs.y);
}
Point operator-(const Point& rhs) const {
return Point(x - rhs.x, y - rhs.y);
}
int operator*(const Point& rhs) const {
return x * rhs.y - y * rhs.x;
}
Point operator/(int divisor) const {
return Point(x / divisor, y / divisor);
}
bool operator==(const Point& rhs) const {
return (x == rhs.x) && (y == rhs.y);
}
bool operator<(const Point& rhs) const {
return x < rhs.x || (x == rhs.x && y < rhs.y);
}
};
赋值运算符重载(例如: = ):
class Matrix {
private:
int rows, cols;
int* data;
public:
Matrix& operator=(const Matrix& other) {
if (this != &other) {
}
return *this;
}
};
函数调用运算符重载( () ):
class Calculator {
public:
int value;
int operator()(int x) {
return value + x;
}
};
下标运算符重载( [] ):
class Array {
private:
int* data;
int size;
public:
int& operator[](int index) {
return data[index];
}
const int& operator[](int index) const {
return data[index];
}
};
成员访问箭头运算符重载( -> ):
class Handle {
private:
int* ptr;
public:
Handle(int* p) : ptr(p) {}
int* operator->() {
return ptr;
}
};