C2556:重载函数仅按返回类型不同 我正在阅读有效的C++,它告诉我“成员函数只有它们的一致性才能被重载”。p>

C2556:重载函数仅按返回类型不同 我正在阅读有效的C++,它告诉我“成员函数只有它们的一致性才能被重载”。p>,c++,constants,C++,Constants,书中的例子是: class TextBlock { public: const char& operator[](std::size_t position) const; char& operator[](std::size_t position); private: std::string text; } 下面的示例使用存储的指针 class A { public: A(int* val) : val_(val) {} int* get_m

书中的例子是:

class TextBlock {
public:
   const char& operator[](std::size_t position) const;
   char& operator[](std::size_t position);

private:
   std::string text;
}
下面的示例使用存储的指针

class A  {
public:
   A(int* val) : val_(val) {}

   int* get_message() { return val_; }

   const int* get_message() { return val_; } const;

private:
   int* val_;
};
我得到:

错误C2556:'const int*A::get_message(void)':重载函数仅在返回类型上与'int*A::get_message(void)'不同


有什么区别?有什么方法可以修复该类,使我有一个常量和非常量版本的get_message吗?

您将
get_message()函数的
const
限定符放在了错误的位置:

const int* get_message() const { return val_; }
//                       ^^^^^
//                       Here is where it should be

额外的
}
之后的code>?原始语句的意思是什么?@StevenMailall:没什么,它在语法上是不正确的。OP很可能认为,由于
const
在书中的示例(仅声明函数)中出现在“分号之前”,因此即使函数体内联在类定义中,它也必须出现在“分号之前”。但同样,这是一个错误。@user619818:发生在每个人身上;)你混淆了函数返回的常量和函数本身的常量。