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


在同一作用域内,可以对同一函数名使用多个定义。函数的定义必须通过参数列表中的类型和/或参数的数量而有所不同。你不能重载仅因返回类型不同而不同的函数声明。

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

以下是使用同一函数 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); // Call print to print integer
   pd.print(500.263); // Call print to print float
   pd.print("Hello C++"); // Call print to print character
   return 0;
}

输出

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

更新日期: 30-7-2019

2000+ 次浏览

启动你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.