函数名称后不久就会出现const类型限定符

Vij*_*jay 11 c++ const member-functions

在C++中,有时我会看到如下声明:

return_type function_name(  datatype parameter1, datatype parameter2  ) const
{ /*................*/}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,这个const类型限定符的确是什么?

Dre*_*all 15

成员函数声明末尾的const限定符表示可以在本身为const的对象上调用该函数.const成员函数承诺不会更改任何非可变数据成员的状态.

当然,const成员函数也可以在非const对象上调用(并且仍然具有相同的承诺).

成员函数也可以在const-isss上重载.例如:

class A {
  public:
    A(int val) : mValue(val) {}

    int value() const { return mValue; }
    void value(int newVal) { mValue = newVal; }

  private:
    int mValue;
};

A obj1(1);
const A obj2(2);

obj1.value(3);  // okay
obj2.value(3);  // Forbidden--can't call non-const function on const object
obj1.value(obj2.value());  // Calls non-const on obj1 after calling const on obj2
Run Code Online (Sandbox Code Playgroud)


Chu*_*dad 9

$ 9.3.1/3状态 -

"非静态成员函数可以声明为const,volatile或const volatile.这些cvqualifiers影响this指针的类型(9.3.2).它们也影响成员函数的函数类型(8.3.5);成员函数声明const是一个const成员函数,一个成员函数声明volatile是一个volatile成员函数,一个成员函数声明const volatile是一个const volatile成员函数."

所以这是摘要:

a)const限定符只能用于类非静态成员函数

b)cv参与超载的功能资格

struct X{
   int x;
   void f() const{
      cout << typeid(this).name();
      // this->x = 2;  // error
   }
   void f(){
      cout << typeid(this).name();
      this->x = 2;    // ok
   }
};

int main(){
   X x;
   x.f();         // Calls non const version as const qualification is required
                  // to match parameter to argument for the const version

   X const xc;
   xc.f();        // Calls const version as this is an exact match (identity 
                  // conversion)
}
Run Code Online (Sandbox Code Playgroud)


Sha*_* D. 5

这意味着它不会修改对象,因此您可以使用 const 对象调用该方法。

IE

class MyClass {
public:
   int ConvertToInteger() const;

};
Run Code Online (Sandbox Code Playgroud)

意味着如果你有

const MyClass myClass;
Run Code Online (Sandbox Code Playgroud)

你可以打电话

int cValue = myClass.ConvertToInteger();
Run Code Online (Sandbox Code Playgroud)

没有编译错误,因为方法声明表明它不会更改对象的数据。