class arbit
{
int var;
public:
int method1();
int method1() const;
};
为什么在这里声明同一个函数两次,g++没有发出警告?
class arbit
{
int var;
public:
int method1();
int method1() 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
即可实现。但请忘记我曾经告诉过你这个方法。您还可以使用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
const
上进行重载非常有用。例如,查看std::vector
中的operator[]
。 - Fred Larsonarbit x; static_cast<const arbit&>(x).method1();
将对象变为 const。 - GManNickG