2010-08-13 108 views
7

在C++中,有时我看到类似下面的声明后不久:常量类型限定符函数名

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

是什么const型修饰词确切在这种情况下怎么办?

回答

7

$ 9.3.1/3明─

“A非静态成员函数可以被声明为const,易失性或const挥发性的。这些cvqualifiers影响该指针(9.3.2)的类型。它们还影响成员函数的函数类型(8.3.5);声明为const的成员函数是const成员函数,声明为volatile的成员函数是volatile成员函数,并且声明为const volatile的成员函数是常量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) 
} 
+0

+ 1为规范性参考! – 2014-12-20 05:50:25

13

成员函数声明结尾的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

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

class MyClass { 
public: 
    int ConvertToInteger() const; 

}; 

意味着,如果你有

const MyClass myClass; 

你可以叫

int cValue = myClass.ConvertToInteger(); 

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