【问题标题】:Is there any way to tell C++11 to use std::string instead of const char*?有没有办法告诉 C++11 使用 std::string 而不是 const char*?
【发布时间】:2021-05-06 07:15:39
【问题描述】:

我正在尝试从允许使用“+”运算符连接字符串的另一种语言迁移代码。

//defintion 
void print(std::string s) {
    std::cout << s;
}
//call
print("Foo " + "Bar");

我遇到的问题是 c++ 将“Foo”和“Bar”视为 const char* 并且无法添加它们,有没有办法解决这个问题。我已经尝试包含字符串库以查看它是否会自动更改它们,但这似乎不起作用。

【问题讨论】:

  • 这能回答你的问题吗? How to concatenate two strings in C++?
  • 不是答案,但在函数之间传递字符串为const std::string&amp; s,而不是std::string s。避免复制并启用优化。

标签: c++ c++11


【解决方案1】:

2个字符串文字情况的最简单解决方案:

print("Foo " "Bar");

否则:

print(std::string("Foo ") + "Bar");

【讨论】:

    【解决方案2】:

    及更高版本:

    using namespace std::literals;
    print("Foo "s + "Bar");
    

    :

    std::string operator "" _s(const char* str, std::size_t len) {
        return std::string(str, len);
    }
    
    print("Foo "_s + "Bar");
    

    或者,在所有版本中:

    print(std::string("Foo ") + "Bar");
    

    【讨论】:

    • 这通常是一个很好的解决方案,但正如 OP 在评论中所说:“我忘了提到我在 c++11”,所以这不会t 专门为 OP 工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2021-10-15
    • 2013-03-07
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多