如何调用类Constant Getter功能超载
我有一个具有2个过载Getter功能的课程。一个返回参考,另一个返回常数参考。我想知道调用第二个功能的方式。无论我尝试做什么,它总是称为第一个功能。
class MyClass
{
private:
std::vector<int> myArray = { 0, 10 };
public:
int& getElement() { return myArray[0]; }
const int& getElement() const { return myArray[1]; }
};
int main()
{
MyClass c;
int& a = c.getElement();
const int& b = c.getElement();
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
}
结果:
a = 0
b = 0
I have a class with 2 overload getter functions. One returns a reference and the other a constant reference. I would like to know the way to call the second function. Whatever I try to do, it always calls the first function.
class MyClass
{
private:
std::vector<int> myArray = { 0, 10 };
public:
int& getElement() { return myArray[0]; }
const int& getElement() const { return myArray[1]; }
};
int main()
{
MyClass c;
int& a = c.getElement();
const int& b = c.getElement();
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
}
result:
a = 0
b = 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论