繁体   English   中英

如何在C ++中调用此成员函数?

[英]How to invoke this member function in C++?

是否可以调用此成员int MyClass::get(int key) const而不是int& MyClass::get(int key) 换句话说,在C ++源代码中,可以使用值而不是引用?

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass(int input) : i(input) {};
    int i;

    int get(int key) const {
        std::cout << "int get(int key) const " << key << std::endl;
        return i; 
    }

    int& get(int key) {
        std::cout << "int& get(int key) " << key << std::endl;
        return i;
    }
};

void dummy(const int helpme)
{
    std::cout << helpme << std::endl;
}

int main() {
    // your code goes here
    MyClass abc(6);
    std::cout << abc.get(13) << std::endl;
    int result = (int)abc.get(16);
    dummy(abc.get(18));
    return 0;
}

最简单的解决方案是使用const &到您的变量。 有两种简单的方法

const auto & abc_const = abc;
std::cout << abc_const.get(13) << std::endl;

要么

std::cout << static_cast<const MyClass&>(abc).get(13) << std::endl;

编辑:看起来你试图根据返回类型选择一个基于以下两行的重载:

int result = (int)abc.get(16);
dummy(abc.get(18));

请参阅此答案,说明在重载解析期间从不使用返回类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM