1
int& MyClass::get(int key)
の代わりにこのメンバーint MyClass::get(int key) const
を呼び出すことはできますか?言い換えれば、C++ソースコードのどこに値を使用できますが、参照は使用できませんか?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;
}
なぜあなたは旧式のキャストを '(int)abc.get(16)'に持っていますか? –
C++ 17では、 'std :: as_const(abc).get(...)'を使うことができます。それ以外の場合は、 'abc'を' const MyClass& 'にバインドすることができます。私はこの種のデザインを推奨していませんが、 – KABoissonneault