C++ 中的函数重载和返回类型

c++server side programmingprogramming更新于 2025/5/6 12:37:17

您可以在同一范围内对同一函数名称进行多次定义。函数的定义必须在类型和/或参数列表中的参数数量方面有所不同。您不能重载仅返回类型不同的函数声明。

函数重载基本上是编译时多态性。它检查函数签名。如果签名不相同,则可以重载它们。函数的返回类型不会对函数重载产生任何影响。具有不同返回类型的相同函数签名将不会被重载。

以下是使用相同函数 print() 打印不同数据类型的示例

示例代码

#include <iostream>
using namespace std;
class printData {
   public:
      void print(int i) {
         cout << "Printing int: " << i << endl;
      }
      void print(double f) {
         cout << "Printing float: " << f << endl;
      }
      void print(char* c) {
         cout << "Printing character: " << c << endl;
      }
};
int main(void) {
   printData pd;
   pd.print(5); // 调用 print 打印整数
   pd.print(500.263); // 调用 print 打印浮点数
   pd.print("Hello C++"); // 调用 print 打印字符
   return 0;
}

输出

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

相关文章