在C++类中重新声明一个函数

Ami*_*mit 5 c++

class arbit
    {
        int var;
        public:

        int method1();
        int method1() const;

    };
Run Code Online (Sandbox Code Playgroud)

为什么g ++在这里两次声明相同的函数时不会发出警告?

Tho*_*mas 15

因为一个是const,另一个不是.这些是不同的重载,具有不同的签名.根据您调用它的对象是否,调用其中一个或另一个const.

例:

arbit x;
x.method1(); // calls the non-const version
arbit const &y = x;
y.method1(); // calls the const version
Run Code Online (Sandbox Code Playgroud)

您应该声明一个方法,就const好像它不会修改对象的(可见)状态.这允许你const arbit分发对象,并确保有人不会意外地修改它们.

例如,你可以使一个函数setValueconst(因为它修改了对象),但是getValueconst.所以在一个const物体上,你可以打电话getValue但不打电话setValue.


¹当有遗嘱时,有一种方法,而且它被称为const_cast.但忘了我告诉过你.