C++ 函数要点
参数
- 如果使用引用形参唯一目的是避免复制实参时,将形参定义成const引用;
- 非const引用形参只能与完全同类型的非const对象关联(不允许类型转换或者直接传递右值);
- 当编译器检查数组形参时,不会检查数组的长度;
- 通过引用传递包含数组长度的形参时,编译器会检查数组长度。
返回值
不可以返回局部对象的指针或者引用,因为局部对象内存在函数出口处释放,将产生野指针。
内联
内联函数应该在头文件中定义。
const成员函数
const对象、指向const对象的指针或引用只能用于调用其const成员函数。
重载
有(const引用形参)或者(指向const类型指针 形参)的函数 与有(非const引用形参)或者(指向非const类型指针 形参)的函数属于重载函数。 #include<iostream>
#include<string> using namespace std; using std::string; void fun(const string &a) { cout<<"fun1"<<endl; } void fun(string &a) { cout<<"fun2"<<endl; } void fun(const char* a) { cout<<"fun3"<<endl; } void fun(char* a) { cout<<"fun4"<<endl; } void main() { const string str = "hello world"; fun(str);
const char* p = NULL; fun(p); }

浙公网安备 33010602011771号