C2556:重载函数仅因返回类型而异

Ang*_*ber 4 c++ const

我正在阅读Effective C++,它告诉我''成员函数只能通过它们的const可以重载'.

书的例子是:

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

private:
   std::string text;
}
Run Code Online (Sandbox Code Playgroud)

我的例子如下,使用存储的指针.

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

   int* get_message() { return val_; }

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

private:
   int* val_;
};
Run Code Online (Sandbox Code Playgroud)

我明白了:

错误C2556:'const int*A :: get_message(void)':重载函数的区别仅在于'int*A :: get_message(void)'的返回类型

有什么不同?有什么方法可以修复这个类,所以我有一个const和非const版本的get_message?

And*_*owl 15

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

const int* get_message() const { return val_; }
//                       ^^^^^
//                       Here is where it should be
Run Code Online (Sandbox Code Playgroud)