C++之函数重载
所谓重载,就是赋予新的含义。函数重载(Function Overloading)可以让一个函数名有多种功能,在不同情况下进行不同的操作。 函数重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但是它们的参数列表和定义(实现)不相同。 在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。不能仅通过返回类型的不同来重载函数。
#include <iostream>
using namespace std;
class Father {
private:
int w;
int h;
public:
Father(int w, int h);
virtual ~Father();
void print(int a);
void print(double b);
void print(Father father);
};
Father::Father(int w, int h) : w(w), h(h) { cout << "Father constructed is created" << endl; }
Father::~Father() { cout << "Father destructed is used" << endl; }
void Father::print(int a) { cout << "print_int:" << a << endl; }
void Father::print(double b) { cout << "print_double:" << b << endl; }
void Father::print(Father father) { cout << "print_father.w:" << father.w << endl; }
int main() {
Father father(1, 2);
father.print(3);
father.print(5.5);
father.print(father);
return 0;
}
输出:
Father constructed is created
print_int:3
print_double:5.5
print_father.w:1
Father destructed is used
Father destructed is used
|