c++ - 通过连接另一个 char* 来初始化 const char*

标签 c++ initialization concatenation const-char

我要重构:

const char* arr = 
  "The "
  "quick "
  "brown";

变成类似的东西:

const char* quick = "quick ";
const char* arr = 
  "The "
  quick
  "brown";

因为字符串“quick”被用在很多其他地方。理想情况下,我需要能够只使用 const 原始类型来做到这一点,所以没有字符串。执行此操作的最佳方法是什么?

最佳答案

以答案的形式编译评论:

  1. 使用宏。

    #define QUICK "quick "
    
    char const* arr = "The " QUICK "brown";
    
  2. 使用std:string

    std::string quick = "quick ";
    std::string arr = std::string("The ") + quick + "brown";
    

工作代码:

#include <iostream>
#include <string>

#define QUICK "quick "

void test1()
{
   char const* arr = "The " QUICK "brown";
   std::cout << arr << std::endl;
}

void test2()
{
   std::string quick = "quick ";
   std::string arr = std::string("The ") + quick + "brown";
   std::cout << arr << std::endl;
}

int main()
{
   test1();
   test2();
}

输出:

The quick brown
The quick brown

关于c++ - 通过连接另一个 char* 来初始化 const char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26807775/

相关文章:

javascript - Node.js 连接反斜杠问题

c++ - 垃圾收集器 : data structure of the object graph

c++ - 在 Windows 中将 libmysql.lib 与 gcc 或 dev c++ 链接起来

c++ - enable_if 和自动返回类型?

constructor - 使用构造函数初始化 F# 对象

mysql - 创建哈希的 SQL 语法

CSS attr() 与 url 路径的连接

c++ - 内部静态和捕获的可变之间的 Lambda 状态行为差异

C 中初始化的结构成员不能用作整型常量吗?

Swift 3 单元测试抛出编译错误 "Cannot convert value ' Type' to 'Type' "