【翁恺】22-引用再研究

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++ 难在内存模型!!!加油掌握它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理心炼丹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值