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

标签 c++ constants

我有这样一个类:

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/

相关文章:

c++ - 如何有效地合并 TBB 线程的结果

c++ - 如何将列的宽度调整为CListCtrl中最长字符串的宽度?

c++ - 固定成员

c++ - 在 C++ 中动态调用静态 "constructor"

c++ - 如何构造通过 std::allocator::allocate() 分配的对象?

c++ - 尝试使用 MinGW 编译 Assembly + C++ : ccqKAvXJ. o :main. cpp :(. text+0x18): undefined reference to `GetMagicNumber'

c++ - const int *p 与 int const *p - 类型后的 const 是否可以接受?

objective-c - 变量声明中const关键字定位的意义

c++ - 为什么 CopyConstructible 定义提到 "rvalue expression of const T"?

android - 安卓编码标准