可以在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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短