错误C2678:binary'=':找不到运算符,它接受类型为'const std :: string'的左手操作数(或者没有可接受的转换)

Avi*_*ash 9 c++ visual-studio

我真的很困惑为什么我得到以下编译错误.Microsoft Visual Studio编译器.

error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion)

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <iterator>

class MyException {
public:
    MyException(    std::string message, 
                        int line = 0) : m_message(message),
                                        m_line(line) {}
    const char* what() const throw(){
        if ( m_line != 0 ) {
            std::ostringstream custom_message;
            custom_message << "Parsing Error occured at ";
            custom_message << m_line << " Line : ";
            custom_message << m_message;        
            m_message = custom_message.str();
        }
        return m_message.c_str();
    }
private:
    std::string m_message;
    int m_line;
};
int main(int argc, char **argv) {
    try {
        // do something
    }catch(MyException &e){
        std::cout << e.what();
    }
}
Run Code Online (Sandbox Code Playgroud)

错误即将到来 m_message = custom_message.str();

joh*_*ohn 20

您将方法声明为const

const char* what() const throw(){
Run Code Online (Sandbox Code Playgroud)

但是你试着改变对象

m_message = custom_message.str();
Run Code Online (Sandbox Code Playgroud)

所以你得到一个错误.

你应该做的是在构造函数中构造自定义消息.

class MyException {
public:
    MyException(const std::string& message, int line = 0) : 
        m_message(message), m_line(line) {
        if ( m_line != 0 ) {
            std::ostringstream custom_message;
            custom_message << "Parsing Error occured at ";
            custom_message << m_line << " Line : ";
            custom_message << m_message;        
            m_message = custom_message.str();
        }
    }
    const char* what() const throw(){
        return m_message.c_str();
    }
private:
    std::string m_message;
    int m_line;
};
Run Code Online (Sandbox Code Playgroud)

我还改变了你的代码,通过引用传递std :: string,这是通常的做法.