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++
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP