可以在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 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短