c ++中的const参数和const方法

man*_*ans 2 c++ const

我有一个这样的课:

class MyClass
{
    const int GetValue()
    {   
        return 2;
     }
}
Run Code Online (Sandbox Code Playgroud)

我将它传递给这样的函数:

void Test(const MyClass &myClass)
{
   int x=myClass.GetValue();
}
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误:

The object has type qualifiers that are not compatible with member function Object type is const MyClass
Run Code Online (Sandbox Code Playgroud)

我知道如果我定义这样的函数:

void Test( MyClass &myClass)
Run Code Online (Sandbox Code Playgroud)

但我想知道为什么添加const会产生这样的错误?

jua*_*nza 8

您需要创建成员函数const,而不是返回类型:

int GetValue() const;
Run Code Online (Sandbox Code Playgroud)

这使得可以在const实例上(或通过const引用或指针)调用此成员.

注意:当您按值返回时,返回的东西的常量与返回它的对象的常量分离.实际上,您不太可能希望返回类型const.