C++重载操作符部分示例
1. 算术操作符:+
#include <iostream>
class Complex {
public:
double real, imag;
Complex(double r, double i) : real(r), imag(i) {
}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
};
int main() {
Complex a(1.0, 2.0), b(3.0, 4.0);
Complex result = a + b;
std::cout << "Result: " << result.real << " + " << result.imag << "i\n";
return 0;
}
2. 比较操作符:==
#include <iostream>
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {
}
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
int main() {
Point p1(1, 2), p2(1, 2), p3(3, 4);
std::cout << "p1 == p2: " << (p1 == p2) << "\n";
std::cout << "p1 == p3: " << (p1 == p3) << "\n";
return 0;
}
3. 赋值操作符:+=
#include <iostream>
class Counter {
public:
int value;
Counter() : value(0) {
}
Counter& operator+=(int increment) {
value += increment;
return *this;
}
};
int main() {
Counter counter;
counter += 5;
std::cout << "Counter: " << counter.value << "\n";
return 0;
}
4. 流操作符:<<
#include <iostream>
class Vector2D {
public:
double x, y;
Vector2D(double x, double y) : x(x), y(y) {
}
friend std::ostream& operator<<(std::ostream& os, const Vector2D& vec) {
os << "(" << vec.x << ", " << vec.y << ")";
return os;
}
};
int main() {
Vector2D vec(1.0, 2.0);
std::cout << "Vector: " << vec << "\n";
return 0;
}
5. 下标操作符:[]
#include <iostream>
class Array {
int* data;
size_t size;
public:
Array(size_t size) : size(size), data(new int[size]) {
}
~Array() {
delete[] data;
}
int& operator[](size_t index) {
return data[index];
}
};
int main() {
Array arr(3);
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
for (size_t i = 0; i < 3; ++i) {
std::cout << "arr[" << i << "] = " << arr[i] << "\n";
}
return 0;
}
6. 函数调用操作符:()
#include <iostream>
class Adder {
int value;
public:
Adder(int value) : value(value) {
}
int operator()(int x) const {
return x + value;
}
};
int main() {
Adder addFive(5);
std::cout << "Add 5 to 3: " << addFive(3) << "\n";
return 0;
}
文章评论