可以在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: 10Value of string y: Hello
Value of x and y: 15, 25
以上是 可以在C ++中重载main()吗? 的全部内容, 来源链接: utcz.com/z/345634.html