C++函数重载
首先,我们在主程序的类中写入连个同名的函数。
#include <iostream>
using namespace std;
class point {
public:
void say_hello(){
cout << "hello world !" << endl;
}
void say_hello(){
cout << "hello cpp !" << endl;
}
};
int main()
{
point *p = new point();
p -> say_hello();
delete p;
return 0;
}
此时,明显是会报错(重复定义),因为两个函数,类型和传入参数都是一样的。我们现在来稍微来改下。
#include <iostream>
#include<cstdio>
using namespace std;
class point {
public:
void say_hello(){
cout << "hello world !" << endl;
}
void say_hello(char *str){
printf("hello %s !\n", str);
}
};
int main()
{
point *p = new point();
p -> say_hello();
delete p;
return 0;
}
当我们像这样不传入参数,输出的则是“hello world !”。
而当我们传入一个参数时:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
class point {
public:
void say_hello(){
cout << "hello world !" << endl;
}
void say_hello(char *str){
printf("hello %s !\n", str);
}
};
int main()
{
point *p = new point();
char a[10] = "cpp";
p -> say_hello(a);
delete p;
return 0;
}
此时的输出就是“hello cpp !” 了。