如何调用类Constant Getter功能超载

发布于 2025-02-12 12:42:55 字数 623 浏览 2 评论 0原文

我有一个具有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文