const functions 总结

1. const 放在函数的后面

     const 放在函数后面,只有成员函数声明为const 才有意义,const函数里面才有const this 指针。表示不会改变类的成员(除非该class 为 mutable),另外const函数的中隐含的this 指针也变为const this 指针。 

     如下 MyClass 中Foo(*this,) const, 可以理解为 Foo(const *this) const

#include <iostream>

class MyClass
{
private:
    int counter;
public:
    void Foo()
    { 
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        std::cout << "Foo const" << std::endl;
    }

};

int main()
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
}

如下const 函数不允许修改类的成员变量
 

    void Foo()
    {
        counter++; //this works
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++; //this will not compile
        std::cout << "Foo const" << std::endl;
    }
    const 函数可以在非const对象中引用,但是非const函数不可以被const对象引用
class foobar {
  ...
  const char* bar();
}


void func1(const foobar& fb1, foobar& fb2) {
  const char* v1 = fb1.bar();  // won't compile
  const char* v2 = fb2.bar();  // works
}



2.const 放在函数的前面

     const 放在函数的前面,表示是返回一个const 指针或者引用。

const T& data() const { return data_; }

Class c;
T& t = c.data()             // Not allowed.
const T& tc = c.data()      // OK.

关于不可对const & 类型进行赋值,在《Effective c++》 中有个例子

class TextBlock{
public:
...
const char& operator[] (std::size_t position) const
{return text[position];}
char& operator(std::size_t position)
{return text[position];}
private:
std::string text;
};


const TextBlock ctb("Word")
TextBlock tb("hello")

std::cout << tb[0]; // ok
tb[0] = 'x';               //ok
std::cout<<ctb[0];   //ok
ctb[0] = 'x' ;            //error



 Refference:

http://www.cprogramming.com/tutorial/const_correctness.html

http://stackoverflow.com/questions/16449889/why-using-the-const-keyword-before-and-after-method-or-function-name

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不负初心

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

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

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

打赏作者

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

抵扣说明:

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

余额充值