void const f() is equivilent to const void f(), which means the return type (in this case a void) is const. This is totally meaningless not only because it's a void (there is nothing there that needs a const qualifier), but also because it's a return type (returning
something as const doesn't make a whole lot of sense).
void f() const makes the function itself const. This only really has meaning for member functions. Making a member function const means that it cannot call any non-const member functions, nor can it change any member variables. It also means that the function can be called via a const object of the class.
class A
{
public:
void Const_No(); // nonconst member function
void Const_Yes() const; // const member function
};
//-----------
A obj_nonconst; // nonconst object
obj_nonconst.Const_No(); // works fine
obj_nonconst.Const_Yes(); // works fine
const A obj_const = A(); // const object
obj_const.Const_Yes(); // works fine (const object can call const function)
obj_const.Const_No(); // ERROR (const object cannot call nonconst function)
类成员函数中const的使用
一般放在函数体后,形如:void fun() const;
任何不会修改数据成员的函数都因该声明为const类型。如果在编写const成员函数时,不慎修改了数据成员,或者调用了其他非const成员函数,编译器将报错,这大大提高了程序的健壮性。
void f() const makes the function itself const. This only really has meaning for member functions. Making a member function const means that it cannot call any non-const member functions, nor can it change any member variables. It also means that the function can be called via a const object of the class.
class A
{
public:
void Const_No(); // nonconst member function
void Const_Yes() const; // const member function
};
//-----------
A obj_nonconst; // nonconst object
obj_nonconst.Const_No(); // works fine
obj_nonconst.Const_Yes(); // works fine
const A obj_const = A(); // const object
obj_const.Const_Yes(); // works fine (const object can call const function)
obj_const.Const_No(); // ERROR (const object cannot call nonconst function)
类成员函数中const的使用
一般放在函数体后,形如:void fun() const;
任何不会修改数据成员的函数都因该声明为const类型。如果在编写const成员函数时,不慎修改了数据成员,或者调用了其他非const成员函数,编译器将报错,这大大提高了程序的健壮性。

本文详细解析了C++中const修饰符的不同用法及其意义,重点介绍了const如何用于函数返回类型及成员函数,强调了其对于提高程序健壮性的作用。

被折叠的 条评论
为什么被折叠?



