1

我想重构:

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

变成类似的东西:

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

因为在很多其他地方都使用了字符串“quick”。理想情况下,我需要能够只使用 const 原始类型来做到这一点,所以没有字符串。做这个的最好方式是什么?

4

1 回答 1

3

以答案的形式编译评论:

  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
于 2014-11-07T18:47:04.037 回答