[英]Member function with const modifier.
I have a class with two member functions which are differ only by const
modifier. 我有一个带有两个成员函数的类,它们的区别仅在于const
修饰符。
class CFoo
{
private:
int x;
int y;
public:
static int a;
void dosmth() const {
a = 99;
}
void dosmth(){
x++;
y++;
}
};
int CFoo::a = 100;
int main(){
CFoo foo;
cout << CFoo::a << endl;
foo.dosmth();
cout << CFoo::a << endl;
}
The following code prints 100, 100
. 以下代码打印100, 100
。 Why is non-const dosmth being called? 为什么要调用非常量用法? How can I call const
version explicitly? 如何显式调用const
版本?
Why is non-const dosmth being called? 为什么要调用非常量用法?
That is by design. 那是设计使然。 If you have a non-const object, the non-const overload is chosen over the const
one. 如果你有一个非const对象,非const超载选择在const
之一。
ow can I call const version explicitly? 我可以显式调用const版本吗?
You need a context where your object is const
. 您需要一个对象为const
的上下文。 For example, 例如,
void dofoo(const Foo& f) { f.dosmth(); }
int main()
{
CFoo foo;
dofoo(foo);
cout << CFoo::a << endl;
or 要么
int main()
{
const CFoo foo1{};
foo1.dosmth();
CFoo foo2;
const_cast<const CFoo&>(foo2).dosmth();
}
The const version is only called when the object itself is const. 仅当对象本身是const时才调用const版本。 This means you can call the const version with this code: 这意味着您可以使用以下代码调用const版本:
int main(){
const CFoo foo;
cout << CFoo::a << endl;
foo.dosmth();
cout << CFoo::a << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.