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

const parameter and const method in c++

本文关键字:const 方法 参数 c++ 中的      更新时间:2023-10-16

我有一个这样的类:

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

您将int设置为const,尝试使方法const如下:

const int GetValue() const
{   
    return 2;
}

有两个问题,一个是可见性问题(您的const int GetValue()函数由于私有而不可见),另一个是您正在调用一个非常量函数(它可以对将其作为成员函数的对象执行修改)

const int GetValue()

从一个常量引用到类

const MyClass &myClass

你基本上是在要求"这个对象不应该被修改,无论如何,让我调用一个不能保证这一点的函数"。

你不够连贯。