代码之家  ›  专栏  ›  技术社区  ›  Vijay

函数名[duplicate]后不久的常量类型限定符

  •  10
  • Vijay  · 技术社区  · 16 年前

    return_type function_name(  datatype parameter1, datatype parameter2  ) const
    { /*................*/}
    

    在这种情况下,const类型限定符exact做什么?

    3 回复  |  直到 12 年前
        1
  •  10
  •   Chubsdad    16 年前

    非静态成员函数可以声明为const、volatile或const volatile。这些限定符影响这个指针的类型(9.3.2)。它们还影响成员函数的函数类型(8.3.5);声明为const的成员函数是const成员函数,声明为volatile的成员函数是volatile成员函数,声明为const volatile的成员函数是const volatile成员函数。”

    总结如下:

    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)
    }
    
        2
  •  19
  •   Georg Fritzsche    16 年前

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

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

    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
    
        3
  •  5
  •   Shawn D.    16 年前

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

    class MyClass {
    public:
       int ConvertToInteger() const;
    
    };
    

    const MyClass myClass;
    

    int cValue = myClass.ConvertToInteger();
    

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

    推荐文章