在前边的学习中,我们知道C++中支持函数的重载,并且知道函数重载有一下几个特性:
-函数重载的本质是相互独立的不同函数
-C++中通过函数名和函数参数确定函数调用
-无法直接通过函数名得到重载函数的入口地址
-函数重载必然发生在同一个作用域中
既然函数重载的要求是以上几点,那很明显,类中的成员函数也可以发生重载,而我们知道,类中的成员函数有
-构造函数
-普通成员函数
-静态成员函数
下边我们就对上边类中的三种成员函数进行重载
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
//构造函数重载
test()
{
cout << "I'm test()" << endl;
}
test(int i)
{
cout << "I'm test(int i)" << endl;
}
test(int i, int j)
{
cout << "I'm test(int i, int j)" << endl;
}
//普通成员函数重载
void fun(int i)
{
cout << "I'm fun(int i)" << endl;
}
void fun(int i, int j)
{
cout << "I'm fun(int i, int j)" << endl;
}
static int fun(int i, int j, int k) //静态成员函数与普通成员函数之间的重载
{
cout << "I'm fun(int i, int j, int k)" << endl;
}
//静态成员函数重载
static void staticFun(int i)
{
cout << "I'm staticFun(int i)" << endl;
}
static void staticFun(int i, int j)
{
cout << "I'm staticFun(int i, int j)" << endl;
}
};
int main()
{
test t1; //调用构造函数test()
test t2(1); //调用构造函数test(int i)
test t3(2,3); //调用构造函数test(int i, int j)
cout << endl;
t1.fun(10); //调用普通成员函数fun(int i)
t1.fun(10, 20); //调用普通成员函数fun(int i, int j)
t1.fun(10, 20, 30); //调用静态成员函数fun(int i, int j, int k)
cout << endl;
test::staticFun(30); //调用静态成员函数staticFun(int i)
test::staticFun(20, 30);//调用静态成员函数staticFun(int i)
system("pause");
}
编译输出如下:
从输出可以得出,类中的三类函数是可以进行重载的,并且普通成员函数与静态成员函数之间也能重载
那么我们来思考一下:类中的成员函数与全局函数之间能进行重载?
答案很明显:不能!上边我们说了,函数重载需要满足如下条件
-函数名与参数列表(参数个数个参数顺序)唯一
-必须发生在同一作用域中
而全局函数与类中成员函数的作用域不同,二者之间必然是不能重载的。