1. 有返回值类型函数(指针函数)
1.1 指针的定义
- 指针:是一个特殊的变量,它里面存储的数值为内存里的一个地址。
- 通过指针,程序员可以直接对内存进行操作。
注:要搞清一个指针需要搞清指针的四方面的内容:指针的类型,指针所指向的类型,指针的值或者叫指针所指向的内存区,还有指针本身所占据的内存区。
1.2 指针作为参数传递回顾
- 形参为指向实参地址的指针,当对形参的指向操作时,就相当于对实参本身进行的操作。
- 将指针作为参数传递的时候,可以在函数里面更改指针里的内容,但是这个指针的内存地址不能被更改,如果要实现更改指针地址,必须传递指向指针的指针作为参数
1.3 指针函数的定义
- 指针函数:指带指针返回的函数,本质是一个函数。
- 指针函数:函数都有返回类型(如果不返回值,则为无值型),只不过指针函数返回类型是某一类型的指针。
- 格式:类型标识符* 函数名(形参列表及类型说明){ //函数体 }
- 好处:在内存中不产生被返回值的副本;
代码示例一:
#include <iostream> using namespace std; class A { public: A(){} ~A(){} public: void set_x(int x){_x=x;} int* get_x(){return &_x;} private: int _x; }; int main() { A *a = new A(); a->set_x(14); int *p = a->get_x(); *p = 24; cout<<"*p="<<*p<<", p="<<p<<endl; cout<<"_x="<<*(a->get_x())<<", &_x="<<a->get_x()<<endl; delete a; system("pause"); return 0; } =>*p=24, p=00254FB8 _x=24, &_x=00254FB8
代码示例二:
#include <iostream> #include <string> #include <map> using namespace std; typedef map<int, string> STR_MAP; class A { public: A(){_str_map.clear();} ~A(){} public: STR_MAP* get_str_map() { return &_str_map; } void insert_to_str_map(int index, string name) { _str_map.insert(pair<int,string>(index, name)); } void show_str_map() { STR_MAP::iterator iter = _str_map.begin(); for(; iter!=_str_map.end(); ++iter) { cout<<"index="<<iter->first<<", name="<<iter->second<<endl; } } private: STR_MAP _str_map; }; int main() { A *a = new A(); int i=0; for(; i<3; i++) { char cstr[16]; string name(itoa(i, cstr, 16)); a->insert_to_str_map(i, "a" + name); } STR_MAP *p = a->get_str_map(); p->insert(pair<int,string>(i, "b")); a->show_str_map(); delete a; system("pause"); return 0; } =>index=0, name=a0 index=1, name=a1 index=2, name=a2 index=3, name=b
注:指针函数是一个函数,只不过这个函数的返回值是一个地址值。函数返回值必须用同类型的指针变量来接受,也就是说,指针函数一定有“函数返回值”,而且在主调函数中,函数返回值必须赋给同类型的指针变量。
1.4 返回指向局部变量的指针
示例代码一:
#include <iostream> using namespace std; int* func() { int a; a = 10; return &a; } int main() { int *p = func(); cout<<"*p="<<*p<<endl; cout<<"*p="<<*p<<endl; system("pause"); return 0; } =>*p=10 *p=272690496
示例代码二:
#include <iostream> #include <string> using namespace std; string* func() { string a; a = 10; return &a; } int main() { string *p = func(); cout<<"*p="<<*p<<endl; cout<<"*p="<<*p<<endl; system("pause"); return 0; } =>编译通过,运行报错 提示:123.exe 中的 0x75644598 处有未经处理的异常: Microsoft C++ 异常: 内存位置 0x00b5ebe8 处的 std::bad_alloc。
参考文献:
[1]《C++全方位学习》范磊——第十三章
[2]《C++程序设计教程(第二版)》钱能——第五章、第六章、第七章
[3]《C++ Primer(第5版)》王刚 杨巨峰——第一章、第六章
[4] 百度搜索关键字:C++函数、指针函数