我有这样一个类:
class MyClass
{
const int GetValue()
{
return 2;
}
}
我将它传递给这样的函数:
void Test(const MyClass &myClass)
{
int x=myClass.GetValue();
}
但是我收到了这个错误:
The object has type qualifiers that are not compatible with member function Object type is const MyClass
我知道如果我这样定义函数:
void Test( MyClass &myClass)
但我想知道为什么添加 const 会产生这样的错误?
最佳答案
您需要使成员函数const
,而不是返回类型:
int GetValue() const;
这使得在 const
实例(或通过 const
引用或指针)上调用此成员成为可能。
注意:当你按值返回时,你返回的东西的常量性与返回它的对象的常量性是分离的。事实上,您不太可能希望返回类型为 const
。
关于c++ - C++中的const参数和const方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25528656/