是 C++保证调用成员函数的某个常量?
如果我有以下内容:
class A {
int foo() const {
j++;
return i;
}
int& foo() {
return i;
}
int i;
mutable int j;
};
那么显然类似
A a;
a.foo() = 5;
调用非常量版本。但是需要满足哪些条件才能确保调用的是 const 或非常量版本,举几个例子......
int i = a.foo(); //I would expect to call the const. Is it guaranteed?
const int j = a.foo(); //Ditto
const int& l = a.foo(); //Ditto
int& k = a.foo(); //I would expect the non-const
foobar(k); //foobar is "void foobar(int)"
return; //but the compiler could potentially decide the const version is fine.
If I have the following:
class A {
int foo() const {
j++;
return i;
}
int& foo() {
return i;
}
int i;
mutable int j;
};
then obviously something like
A a;
a.foo() = 5;
calls the non-const version. But what conditions need to be met to make sure that a call is to the const or non-const version for a few examples...
int i = a.foo(); //I would expect to call the const. Is it guaranteed?
const int j = a.foo(); //Ditto
const int& l = a.foo(); //Ditto
int& k = a.foo(); //I would expect the non-const
foobar(k); //foobar is "void foobar(int)"
return; //but the compiler could potentially decide the const version is fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当对象本身是 const 时,将调用 const 函数。
另请参阅此代码以更好地理解:(必须阅读注释)
请参阅在线演示:http:// /ideone.com/96flE
const
function gets called when the object itself isconst
.Also see this code for better understanding: (must read the comments)
See the online demo : http://ideone.com/96flE
a
的常量决定了哪个函数 - 您对返回值所做的操作不属于重载决策的一部分。您的所有示例都将调用非常量版本。The constness of
a
decides which function - what you do with the return value is not a part of overload resolution. All your samples would call the non-const version.在确定采用哪个重载时,从不考虑返回值。
另外,当
a
声明为 时,非常量版本优先。
如果
a
被声明为那么 const 版本只能被调用。
Return values are never considered when determining which overload to take.
Also, when
a
is declared asthen the non const version takes precedence.
If
a
is declared asthen the const version can be called only.
您的成员函数调用是否解析为 const 成员函数,取决于“this”指针的常量性,即隐式传递给被调用成员函数的点或箭头运算符的 LHS 上的对象。
解析为非 const:
解析为 const:
Whether your member function call resolves to a const member function or not, depends on the constness of the "this" pointer i.e. the object on the LHS of dot or arrow operator that is implicitly passed to the called member function.
Resolves to non const:
Resolves to const: