【发布时间】:2011-03-29 07:06:55
【问题描述】:
在 C++ 中,有时我会看到如下声明:
return_type function_name( datatype parameter1, datatype parameter2 ) const
{ /*................*/}
在这种情况下,这个 const 类型限定符究竟有什么作用?
【问题讨论】:
标签: c++ constants member-functions
在 C++ 中,有时我会看到如下声明:
return_type function_name( datatype parameter1, datatype parameter2 ) const
{ /*................*/}
在这种情况下,这个 const 类型限定符究竟有什么作用?
【问题讨论】:
标签: c++ constants member-functions
成员函数声明末尾的 const 限定符表示该函数可以在本身为 const 的对象上调用。 const 成员函数承诺不会改变任何非可变数据成员的状态。
当然,const 成员函数也可以在非 const 对象上调用(并且仍然做出相同的承诺)。
成员函数也可以在 const-ness 上重载。例如:
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
【讨论】:
$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)
}
【讨论】:
这意味着它不会修改对象,因此您可以使用 const 对象调用该方法。
即
class MyClass {
public:
int ConvertToInteger() const;
};
意味着如果你有
const MyClass myClass;
你可以打电话
int cValue = myClass.ConvertToInteger();
没有编译错误,因为方法声明表明它不会更改对象的数据。
【讨论】: