void f() const 常成员函数

来源:互联网 发布:京东大数据平台架构 编辑:程序博客网 时间:2024/06/05 02:40


const修饰类的成员函数,则该成员函数不能修改类中任何非const成员函数,也不能修改任何成员变量。一般写在函数的最后来修饰。

如:

class A {… void function()const; //常成员函数, 它不改变对象的成员变量. //也不能调用类中任何非const成员函数。}


对于const类对象/指针/引用,只能调用类的const成员函数,因此,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.

0 0