代码之家  ›  专栏  ›  技术社区  ›  Floris

为什么cpp编译器在类型声明不正确时要转换为int?

  •  -1
  • Floris  · 技术社区  · 1 年前

    首先,很抱歉我的英语不好。

    我正在编写一个websocket类,并希望有一个 函数作为参数 构造器 但我 忘记 ":" 宣言 消息处理程序 方法在 WebsocketClient 类。

    编译器一直给我这个错误:

    错误:无法将“std::string”{aka“std::__cxx11::basic_string<char>”}转换为“int”。

    我很困惑,但终于找到了问题所在。 但是为什么编译器不告诉我它无法解析类型呢? (我认为这是问题所在,因为语法错误)

    这是主要代码:

    void ws_msg_handler(std::string &msg_recieved){
      std::cout << "ws_msg_handler: " << msg_recieved << std::endl;
    
    }
    
    WebsocketClient wsClient("ws://my.secret.ip.adress:7777", ws_msg_handler);
    

    这是班级:

    class WebsocketClient {
    
    private:
        
    
        void message_handler(std:string &recieved_msg); // <- here is ":" missing
    
    public:
        char *uri;
    
    
        WebsocketClient(char *uri, void (*message_handler)(std::string&)){
            this->uri = uri;
            this->message_handler = message_handler;
    
    
    
        };
    
    
        void ws_data_receive_handler(esp_websocket_event_data_t *data_recieved){
            
            std::string msg_recieved(data_recieved->data_ptr);
            
            this->message_handler(msg_recieved); // <- here it gives the error: "error: cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'int'"
    
        }
    
    };
    

    我试着在谷歌上搜索,最后问聊天gpt。当我提供最后一条信息时,它能够找出语法错误。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Jarod42    1 年前

    为什么编译器不告诉我它无法解析类型?

    它告诉你第一个错误,我得到:

    <source>:10:26: error: 'std' is not a type
       10 |     void message_handler(std:string &recieved_msg); // <- here is ":" missing
          |                          ^~~
    <source>:10:29: error: expected ',' or '...' before ':' token
       10 |     void message_handler(std:string &recieved_msg); // <- here is ":" missing
          |                             ^
    <source>: In member function 'void WebsocketClient::ws_data_receive_handler(esp_websocket_event_data_t*)':
    <source>:15:31: error: cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'int'
       15 |         this->message_handler(msg_recieved); // <- here it gives the error: "error: cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'int'"
          |                               ^~~~~~~~~~~~
          |                               |
          |                               std::string {aka std::__cxx11::basic_string<char>}
    <source>:10:26: note:   initializing argument 1 of 'void WebsocketClient::message_handler(int)'
       10 |     void message_handler(std:string &recieved_msg); // <- here is ":" missing
          |                          ^~~
    

    Demo

    为了诊断多个错误,编译器必须从之前的错误中“恢复”。用int/ovoid替换未知/格式错误的类型可能是一种方法。不过,这可能会导致“错误”地报告未来的错误。

    所以你必须检查第一个错误才能得到准确的报告。