C++ 重载:函数重载与运算符重载示例

在 C++ 中,重载允许我们为同一个函数名或运算符定义多个不同的实现,从而增强代码的灵活性与可读性。本文将通过一个示例代码,介绍 C++ 中的函数重载和运算符重载。cpp#include

// 函数重载示例void print(int num) { std::cout << '整数: ' << num << std::endl;}

void print(double num) { std::cout << '浮点数: ' << num << std::endl;}

void print(const char* str) { std::cout << '字符串: ' << str << std::endl;}

// 运算符重载示例class Vector {private: double x, y;

public: Vector(double x, double y) : x(x), y(y) {}

Vector operator+(const Vector& other) {        return Vector(x + other.x, y + other.y);    }

Vector operator-(const Vector& other) {        return Vector(x - other.x, y - other.y);    }

void print() {        std::cout << '向量: (' << x << ', ' << y << ')' << std::endl;    }};

int main() { // 函数重载示例 print(42); print(3.14); print('Hello, World!');

// 运算符重载示例    Vector v1(1.0, 2.0);    Vector v2(3.0, 4.0);    Vector v3 = v1 + v2;    Vector v4 = v3 - v2;

v1.print();    v2.print();    v3.print();    v4.print();

return 0;}

代码解析:

  1. 函数重载: 我们定义了三个同名函数 print,分别接受 intdoubleconst char* 类型的参数。当调用 print 函数时,编译器会根据传入参数的类型自动选择合适的函数版本进行调用。

  2. 运算符重载: 我们定义了一个 Vector 类,并重载了 +- 运算符。通过运算符重载,我们可以像操作基本数据类型一样对自定义对象进行操作,例如对两个向量进行加减运算。

总结:

C++ 中的重载机制提高了代码的灵活性和可读性。函数重载允许我们使用相同的函数名处理不同类型的参数,而运算符重载则使我们能够以更直观的方式操作自定义对象。

C++ 重载:函数重载与运算符重载示例

原文地址: http://www.cveoy.top/t/topic/BXi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录