what does const mean in c++ in different places

前端 未结 4 1868
臣服心动
臣服心动 2020-12-06 14:14

What is the difference between

    const string& getName() const {return name;}

and

    string& getName() const {         


        
4条回答
  •  忘掉有多难
    2020-12-06 14:27

    const string& getName() const {return name;}
    

    return const reference means that you will not be able the instance after returning the reference to it.

    string& getName() const {return name;}
    

    const method means that this method will not change the state of the object except the mutable member variables. Also this method can be called on an const object for example:

    class MyClass(){
    public:
      void doSomethingElse()const;
      void notConstMethod();
    };
    
    void doSomething( const MyClass& obj ){
      obj.doSomethingElse();
      obj.notConstMethod(); //Error
    }
    

提交回复
热议问题