|
一、类中的函数重载: 1、函数重载的温习:
2、类中的成员函数可以进行重载:
这里有一个问题:全局函数,普通成员函数以及静态成员函数之间是否可以构成重载? 从上面回顾重载函数的知识中,我们要注意到一点函数重载必须发生在同一作用域里面(其他两点问题不大),所以的构造函数和普通成员函数是可以构造重载的,而与全局函数是不可以构成重载的。 代码测试: #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; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outvoid func() void func(int i),i=1 Test::Test() Test::Test(int i) Test::Test(const Test& obj void func() void Test::func() void func(int i),i=2 void Test::func(int i), i =2 void Test::func() 3、重载的意义:
这里用c语言里面的拷贝字符串函数strcpy来进行扩展演示: 代码版本一: #include <stdio.h>#include <string.h> int main() { const char* s = "linux is great !"; char buf[8] = {0}; strcpy(buf, s); printf("%s\n", buf); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outlinux is great ! *** stack smashing detected ***: ./a.out terminated Aborted (core dumped) 这里虽然结果是输出多了,但是这个程序同时也报了段错误,因为buf所能存储的能力小于s;所以为了解决这个问题,你肯定第一时间想到strncpy函数: 代码版本二: #include <stdio.h>#include <string.h> int main() { const char* s = "linux is great !"; char buf[8] = {0}; strncpy(buf, s,sizeof(buf)-1); printf("%s\n", buf); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outlinux i 这个函数就保护程序的安全性;但是我在c++里面既然学习了函数重载,那么久可以在原有的函数基础上进行扩展: 代码版本三: #include <stdio.h>#include <string.h> char* strcpy(char* buf, const char* str, unsigned int n) { return strncpy(buf, str, n); } int main() { const char* s = "linux is great !"; char buf[8] = {0}; strcpy(buf, s, sizeof(buf)-1); printf("%s\n", buf); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outlinux i 二、总结:
好了,今天的分享就到这里,如果文章中有错误或者不理解的地方,可以交流互动,一起进步。 |
微信公众号
手机版