在 C++ 中,我们可以使用函数重载和运算符重载来提高代码的可读性和复用性。本文将带你深入理解这两个概念,并通过创新示例来展示它们的强大之处。
函数重载允许在同一作用域内定义多个同名但参数列表不同的函数。当调用重载函数时,编译器会根据传递的参数类型和数量,自动选择最匹配的函数版本。
#include
using namespace std;
class Printer {
public:
void print(int num) {
cout << "[整数] " << num << endl;
}
void print(double num) {
cout << "[浮点数] " << num << endl;
}
void print(const string& text) {
cout << "[字符串] " << text << endl;
}
};
int main() {
Printer printer;
printer.print(42);
printer.print(3.14159);
printer.print("Hello, C++!");
return 0;
}
[整数] 42
[浮点数] 3.14159
[字符串] Hello, C++!
int
和 double
类型参数。write()
函数可支持字符串、整数、二进制数据等多种输入。C++ 允许重载大部分运算符,以适应自定义类型的操作。例如,我们可以重载 +
运算符来实现两个对象相加。
+
必须是二元运算,不能改为一元)。.
、::
、sizeof
、?:
等特殊运算符。+
计算体积#include
using namespace std;
class Box {
private:
double length, width, height;
public:
Box(double l = 0, double w = 0, double h = 0) : length(l), width(w), height(h) {}
double getVolume() const {
return length * width * height;
}
Box operator+(const Box& other) const {
return Box(length + other.length, width + other.width, height + other.height);
}
};
int main() {
Box box1(3, 4, 5);
Box box2(6, 7, 8);
Box box3 = box1 + box2;
cout << "Box1 体积: " << box1.getVolume() << endl;
cout << "Box2 体积: " << box2.getVolume() << endl;
cout << "Box3 体积: " << box3.getVolume() << endl;
return 0;
}
Box1 体积: 60
Box2 体积: 336
Box3 体积: 1335
除了成员函数,我们还可以使用友元函数进行重载。这种方法更适用于对称运算符,如 +
、-
等。
class Point {
private:
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
friend Point operator+(const Point& p1, const Point& p2);
void display() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
Point operator+(const Point& p1, const Point& p2) {
return Point(p1.x + p2.x, p1.y + p2.y);
}
int main() {
Point p1(2, 3), p2(5, 7);
Point p3 = p1 + p2;
p3.display();
return 0;
}
(7, 10)
运算符重载本质上也是函数,因此也可以进行函数重载。
class Number {
public:
int value;
Number(int v) : value(v) {}
Number operator+(const Number& num) {
return Number(value + num.value);
}
Number operator+(int num) {
return Number(value + num);
}
};
int main() {
Number n1(10), n2(20);
Number n3 = n1 + n2;
Number n4 = n1 + 100;
cout << "n3: " << n3.value << endl;
cout << "n4: " << n4.value << endl;
return 0;
}
n3: 30
n4: 110
通过本篇博客的讲解,相信你已经掌握了 C++ 运算符重载和函数重载的核心概念及其实际应用。希望这些示例能帮助你更好地编写高效、可读性强的 C++ 代码!