ใน 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() เราสามารถใช้พวกมันเป็นสมาชิกคลาสได้ คีย์เวิร์ดหลักไม่ใช่คีย์เวิร์ดที่จำกัดการใช้งาน เช่น 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