C ++只读数组文字

时间:2014-08-11 01:05:47

标签: c++ literals string-literals

在只读内存上创建数组文字的可能性以字符串文字形式存在,但不会扩展到其他类型。

const char* const kChar1{"This is a name"};
const char kChar2[]={"This is a name"};

const int* const kInt1{5,3,2,6,9,0,0,2};  //error
const int kInt2[]{5,3,2,6,9,0,0,2};

我无法像创建kChar1那样创建KInt1。

我怎样才能创建等效的?

2 个答案:

答案 0 :(得分:4)

这非常接近:

const int kInt2[]{5,3,2,6,9,0,0,2};
const int* const kInt1 = kInt2;

唯一真正的区别是kInt1必然指向与kInt2相同的内存,但kChar1不一定指向与kChar2相同的内存。

答案 1 :(得分:0)

我认为这是正确的

const int one = 5;
const int two = 10;
const int* const kInt1[] ={&one,&two};