为什么成员函数中的 class 类型的 char 数组成员突然变成了 const char 数组类型?

Why is a class member of type char array suddenly of type const char array in member function?

我有以下代码。

#include <exception>

public MyException : public std::exception {
private:
    const char* MESSAGE = "ExceptionReport";

protected:
    static const int MAX_MESSAGE_LENGTH = 200;
    char composedMessage[MyException::MAX_MESSAGE_LENGTH];

public:
    virtual const char* what() const throw() {
        strcpy(this->composedMessage, this->MESSAGE);
        return this->composedMessage,
    }
};

我想知道为什么这不起作用。根据 tu VS 2013 this->composedMessage 使用 strcpy 时突然 const。我见过几个类似的解决方案来初始化 char 数组类型的成员。为什么这对我不起作用?我没看到什么?

我需要 composedMessage 通过 strcatMyException 的子类中添加更多信息。但是,如果它甚至不能以其当前形式工作,那么添加它是没有用的。

what() 标记为 const。因为它是 const 你不能修改函数中的 class 状态(composedMessage)。你可以让 composedMessage mutable 像:

mutable char composedMessage[MyException::MAX_MESSAGE_LENGTH];

这将允许您在 const 函数中更改它。

Live Example