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

时间:2010-08-09 19:32:02

标签: c++

class arbit
    {
        int var;
        public:

        int method1();
        int method1() const;

    };

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

2 个答案:

答案 0 :(得分:15)

因为一个是const而另一个不是。这些是不同的重载,具有不同的签名。调用其中一个,具体取决于您调用它的对象是const

示例:

arbit x;
x.method1(); // calls the non-const version
arbit const &y = x;
y.method1(); // calls the const version

如果方法不修改对象的(可见)状态,则应将方法声明为const。这允许你分发const arbit个对象,并确定有人不会意外地修改它们。

例如,您可以创建一个函数setValue非 - const(因为它会修改对象),但getValue将是const。因此,在const对象上,您可以拨打getValue但不能setValue


¹当有遗嘱时,有一种方式,它被称为const_cast。但忘记我曾经告诉过你。

答案 1 :(得分:3)

您还可以使用volatile修饰符和两者的组合重载:const volatile

#include <iostream>
using namespace std;

class foo {
public:
    void bar()                { cout << "bar()" << endl; }
    void bar() const          { cout << "bar() const" << endl; }
    void bar() volatile       { cout << "bar() volatile" << endl; }
    void bar() const volatile { cout << "bar() const volatile" << endl; }
};

int main() {
    foo f;
    f.bar();

    foo const f_const;
    f_const.bar();

    foo volatile f_volatile;
    f_volatile.bar();

    foo const volatile f_const_volatile;
    f_const_volatile.bar();
}

那将输出:

bar()
bar() const
bar() volatile
bar() const volatile
相关问题