返回引用

Posted on 2016-08-10 20:23  Jay_L_Z  阅读(235)  评论(0编辑  收藏  举报
istream &read(istream &is,Sales_data &item)
{
    double price = 0;
    is>>item.bookNo>>item.units_sold>>price;
    item.revenue = price * item.units_sold;
    return is;
}

这个时候is是经过函数参数传过来的,其实本质上不会随着函数的结束而灭亡,所以是要返回的,但是有的却不是这样,局部引用用完后销毁掉的,所以就不能作为返回值的。

 

class Screen
{
public:
    typedef std::string::size_type pos;
    Screen(pos ht,pos wd,char c):height(ht),width(wd),contents(ht*wd,c){}
    char get() const{return contents[cursor];}
    inline char get(pos ht,pos wd) const;
    Screen &move(pos r,pos c);
private:
    pos cursor;
    pos height,width;
    std::string contents;
};

char get() const函数是一个常成员函数,他只能访问类成员而不能去改变成员的值呀。除非成员定义成mutable,否则真是没办法的事。当然很重要的一部分就是常成员函数对于this指针,将this指针从常量指针变成了指向常量的常量指针。

 

今天看了一天的return *this,简单点,const成员函数返回的是常量引用,如果不是const成员函数就不是常量引用。