1.函数重载回顾
- 函数重载的本质为相互独立的不同函数
- C++中通过函数名和函数参数确定函数调用
- 无法直接通过函数名得到函数重载的入口地址
- 函数重载发生同一个作用域内
2.类中的重载
- 构造函数的重载
- 普通成员函数的重载
- 静态成员函数的重载
3.万变不离其宗
4.类与重载的深度分析
#include <stdio.h>
class Test
{
int i;
public:
Test()
{
printf("Test::Test()\n");
this->i = 0;
}
Test(int i)
{
printf("Test::Test(int i)\n");
this->i = i;
}
Test(const Test& obj)
{
printf("Test(const Test& obj)\n");
this->i = obj.i;
}
static void func()
{
printf("void Test::func()\n");
}
void func(int i)
{
printf("void Test::func(int i), i = %d\n", i);
}
int getI()
{
return i;
}
};
void func()
{
printf("void func()\n");
}
void func(int i)
{
printf("void func(int i), i = %d\n", i);
}
int main()
{
func();
func(1);
Test t; // Test::Test()
Test t1(1); // Test::Test(int i)
Test t2(t1); // Test(const Test& obj)
func(); // void func()
Test::func(); // void Test::func()
func(2); // void func(int i), i = 2;
t1.func(2); // void Test::func(int i), i = 2
t1.func(); // void Test::func()
return 0;
}
5.重载的意义
- 通过函数名对函数功能进行提示
- 通过参数列表对函数用法进提示
- 扩展系统中已经存在的函数功能
6. 编程实验:重载的意义分析
29-2.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
char* strcpy(char* buf, const char* str, unsigned len)
{
return strncpy(buf, str, len);
}
int main()
{
const char* str = "hello cpp";
char buf[10] = { 0 };
strcpy(buf, str, sizeof(buf) - 1);
printf("%s\n", buf);
}
结果:
7.思考
重载能够扩展系统中已经存在的函数功能,那么重载是否也能扩展其他更多的功能,下面的复数解决方案是否可行?
8.小结
- 类的成员函数之间考研进行重载
- 重载必须发生在同一个作用域内
- 全局函数和成员函数不能构成重载关系
- 重载的意义在于扩展已经存在的功能