以类似于初始化字符串文字的方式初始化 char 数组
假设我已经初始化了一个 char 数组:
Suppose I've following initialization of a char array:
char charArray[]={'h','e','l','l','o',' ','w','o','r','l','d'};
我还对字符串文字进行了以下初始化:
and I also have following initialization of a string literal:
char stringLiteral[]="hello world";
第一个数组和第二个字符串的内容之间的唯一区别是第二个字符串的末尾有一个空字符.
The only difference between contents of first array and second string is that second string's got a null character at its end.
当涉及到初始化 char 数组时,是否有宏或其他东西可以让我们将初始化文本放在两个双引号之间,但数组没有额外的空终止字符?
When it's the matter of initializing a char array, is there a macro or something that allows us to put our initializing text between two double quotation marks but where the array doesn't get an extra null terminating character?
对我来说,当不需要终止空字符时,我们应该使用第一次提到的初始化语法并为初始化文本中的每个字符写两个单引号,以及 virgule 标记单独的字符.
It just doesn't make sense to me that when a terminating null character is not needed, we should use syntax of first mentioned initialization and write two single quotation marks for each character in the initializer text, as well as virgule marks to separate characters.
我应该补充一点,当我想要一个 char 数组时,很明显我不想将它与依赖字符串文字的函数一起使用,而且没有使用字符串文字的功能结果,在我的考虑范围内.
I should add that when I want to have a char array, it should also be obvious that I don't want to use it with functions that rely on string literals along with the fact that none of features in which using string literals results, is into my consideration.
感谢您的回答.
推荐答案
我可能已经找到了一种方法来做我想做的事,虽然它不是我想要的,但它可能具有相同的效果.
首先考虑以下两个类:
I might have found a way to do what i want though it isn't directly what I wanted, but it likely has the same effect.
First consider two following classes:
template <size_t size>
class Cont{
public:
char charArray[size];
};
template <size_t size>
class ArrayToUse{
public:
Cont<size> container;
inline ArrayToUse(const Cont<size+1> & input):container(reinterpret_cast<const Cont<size> &>(input)){}
};
在继续之前,您可能想去 在这里,看看常量表达式构造函数和初始化类型.
现在看下面的代码:
Before proceeding, you might want to go here and take a look at constant expression constructors and initialization types.
Now look at following code:
const Cont<12> container={"hello world"};
ArrayToUse<11> temp(container);
char (&charArray)[11]=temp.container.charArray;
最后初始化文本写在两个双引号之间.
Finally initializer text is written between two double quotations.
相关文章