什么是 C++ 的函数重载?它的优点是什么?和重写有什么区别?

什么是 C++ 的函数重载?

在 C++ 中,函数重载(Function Overloading)是指在同一作用域内定义多个同名函数,但这些函数的参数列表不同。编译器会根据调用时传递的参数类型和数量来选择最合适的函数进行调用。函数重载的主要目的是提高代码的可读性和复用性。

函数重载的优点

  1. 提高代码可读性:使用相同的函数名称可以更好地表达功能,使代码更易于理解和维护。
  2. 增强代码复用性:可以通过不同的参数列表实现相同的功能,减少重复代码的编写。
  3. 灵活性:可以根据不同的需求提供多种实现方式,使代码更加灵活。

函数重载的示例

#include <iostream>
#include <string>

// 重载函数:根据不同的参数类型和数量
void print(int num) {
    std::cout << "整数: " << num << std::endl;
}

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

void print(const std::string& str) {
    std::cout << "字符串: " << str << std::endl;
}

int main() {
    print(10);        // 调用 void print(int num)
    print(3.14);      // 调用 void print(double num)
    print("Hello");   // 调用 void print(const std::string& str)

    return 0;
}

函数重载与函数重写的区别

  1. 函数重载(Function Overloading):在同一作用域内定义多个同名函数,但参数列表不同。编译器根据调用时的参数类型和数量选择最合适的函数。不涉及继承关系。
  2. 函数重写(Function Overriding):在派生类中重新定义基类中的虚函数。派生类中的函数必须与基类中的函数具有相同的函数签名(包括返回类型、函数名称、参数列表)。涉及继承关系,通常用于实现多态。

函数重写的示例

#include <iostream>

class Base {
public:
    virtual void display() {
        std::cout << "Base class display" << std::endl;
    }
};

class Derived : public Base {
public:
    void display() override {
        std::cout << "Derived class display" << std::endl;
    }
};

int main() {
    Base* basePtr = new Derived();
    basePtr->display();  // 调用 Derived 类的 display 方法

    delete basePtr;
    return 0;
}

总结

  • 函数重载:在同一作用域内定义多个同名函数,但参数列表不同,提高代码的可读性和复用性。
  • 函数重写:在派生类中重新定义基类中的虚函数,实现多态,涉及继承关系。
#c++笔记#
全部评论

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务