返回char *而不是字符串 [英] Returning char * instead of string

查看:59
本文介绍了返回char *而不是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++ 11中更正以下代码:

How may I correct the following code in C++11:

    const char *what() const noexcept override {
        return "Mtm matrix error: Dimension mismatch: (" + std::to_string(mat1_height) + "," +
               std::to_string(mat1_width)
               + ") (" + std::to_string(mat2_height) + "," + std::to_string(mat2_width) + ")";
    }

如您所见,我返回的是 string 而不是 const char * ,但这不会自动转换吗?以及如何解决?

As you can see I'm returning string instead of const char* but won't that be converrted automatically? and how to fix that?

注意:我想要的东西看起来像c ++代码,而不是c,例如,使用 sprintf

Note: I want something to look like c++ code and not c using sprintf for example

推荐答案

但是那不会自动转换吗?

but won't that be converrted automatically?

否.

以及如何解决?

将字符串存储为成员,然后在 what 中调用 c_str().示例:

Store the string as a member, and call c_str() in what. Example:

struct descriptive_name : std::exception {
    std::string msg;

    descriptive_name(
       int mat1_width,
       int mat1_height,
       int mat2_width,
       int mat2_height)
         : msg(
           "Mtm matrix error: Dimension mismatch: ("
           + std::to_string(mat1_height)
           + ","
           + std::to_string(mat1_width)
           + ") ("
           + std::to_string(mat2_height)
           + ","
           + std::to_string(mat2_width)
           + ")"
           )
    {}

    const char *what() const noexcept override {
        return msg.c_str();
    }
};

甚至更好:从 std :: runtime_error 继承,不要覆盖 what ,并使用消息字符串初始化基类.示例:

Even better: Inherit from std::runtime_error, don't override what, and initialise the base class with the message string. Example:

struct descriptive_name : std::runtime_error {
    descriptive_name(
       int mat1_width,
       int mat1_height,
       int mat2_width,
       int mat2_height)
         : std::runtime_error(
           "Mtm matrix error: Dimension mismatch: ("
           + std::to_string(mat1_height)
           + ","
           + std::to_string(mat1_width)
           + ") ("
           + std::to_string(mat2_height)
           + ","
           + std::to_string(mat2_width)
           + ")"
           )
    {}
};

这篇关于返回char *而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆