C++ 中可对 main() 进行重载吗?
在 C++ 中,我们可以使用函数重载。那么我们心中出现一个问题,我们可以重载 main() 函数吗?
让我们看一个程序来了解这个思想。
示例
#include <iostream>
using namespace std;
int main(int x) {
cout << "Value of x: " << x << "\n";
return 0;
}
int main(char *y) {
cout << "Value of string y: " << y << "\n";
return 0;
}
int main(int x, int y) {
cout << "Value of x and y: " << x << ", " << y << "\n";
return 0;
}
int main() {
main(10);
main("Hello");
main(15, 25);
}输出
This will generate some errors. It will say there are some conflict in declaration of main() function
为了克服 main() 函数,我们可以将它们用作类成员。main 不是像 C++ 中的 C 一样的限定关键字。
示例
#include <iostream>
using namespace std;
class my_class {
public:
int main(int x) {
cout << "Value of x: " << x << "\n";
return 0;
}
int main(char *y) {
cout << "Value of string y: " << y << "\n";
return 0;
}
int main(int x, int y) {
cout << "Value of x and y: " << x << ", " << y << "\n";
return 0;
}
};
int main() {
my_class obj;
obj.main(10);
obj.main("Hello");
obj.main(15, 25);
}输出
Value of x: 10 Value of string y: Hello Value of x and y: 15, 25
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP