references as class members
-
declared without initial value 如果一个类的成员是引用,那么声明的时候没有办法给一个初始值。
-
must be initialized using constructor initializer list
class X{ public: int& m_y; X(int& a); }; X::X(int a):m_y(a){}
returning references
-
functions can return references
-
but they better refer to non-local variables!
#include <assert.h> const int SIZE = 32; double myarray[SIZE]; double& subscript(const int i){ return myarray[i]; }
-
example
main{
for(int i=0;i<SIZE;i++){
mayarray[i]=i*0.5;
}
double value = subscript(12);
subscript(3) = 34.5; // 做左值
}
const in functions arguments
对象送入一个函数,对象可能很大。如果送对象本身,大量数据传递发生,占据很大空间,花费时间做push,某些情况下必须这么做。方法2:送指针进去,函数内部获得对外面对象的控制权,会改变外面的对象。方法3;在指针前面加上const,在函数内无法进行修改该对象,编译器生成的代码不能对对象做修改。方法4:推荐使用, 好处是不需要有很多 * 号。常见做法。const 引用。
-
pass by const value --don’t do it
-
passing by const reference
Person(const string& name,int weight);
- don’t change the string object
- more efficient to pass by reference(address) than to pass by value(copy)
- const qualifier protects from change
const reference parameters
可以任意使用那些引用,但是不能做修改,不能做左值。
-
what if you don’t want the argument changed?
-
use const modifier
//y is constant!can't be modified void func(const int & y,int & z){ z = z*5;//ok y+=5;/error }
temporary values are const
-
what you type
void func(int &); func(i*3);//generates warning or error i*3 不能做左值
输出9.
-
what the compiler generates
void func(int &); const int tem@ = i*3; func(tem@);//problem--bindling cons ref to non-const argument!
const in function returns
-
return by const value
- for user defined types,it means “prevent use as an value”
- for built-in’s it means nothing
-
return by const pointer or reference
- depends on what you want your client to with the return value
C++ 难在内存模型!!!加油掌握它。