const functions 总结

来源:互联网 发布:window 安装ubuntu 编辑:程序博客网 时间:2024/06/11 16:59

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]; // oktb[0] = 'x';               //okstd::cout<<ctb[0];   //okctb[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
原创粉丝点击