I'm a c++ beginner, I want to initialize an array so that the element of the array is actually a reference to a variable.
我是一个c ++初学者,我想初始化一个数组,以便数组的元素实际上是对变量的引用。
string string_1;
string string_2;
string strings[2] = {&string_1, &string_2};
Is this allowed? So any operation done to the array will be applied to the variables string_1
and string_2
themselves?
这是允许的吗?那么对数组所做的任何操作都将应用于变量string_1和string_2本身?
2 个解决方案
#1
3
You can simulate an array of references:
您可以模拟引用数组:
using s_ref = std::reference_wrapper<std::string>;
s_ref strings[] = { std::ref(string_1), std::ref(string_2) };
Or just use pointers (that's really what reference_wrapper
does underneath).
或者只是使用指针(这正是reference_wrapper在下面做的)。
#2
0
Arrays of references is not allowed in C++. Also there can be no pointers to references.
C ++中不允许使用引用数组。也没有指向引用的指针。
#1
3
You can simulate an array of references:
您可以模拟引用数组:
using s_ref = std::reference_wrapper<std::string>;
s_ref strings[] = { std::ref(string_1), std::ref(string_2) };
Or just use pointers (that's really what reference_wrapper
does underneath).
或者只是使用指针(这正是reference_wrapper在下面做的)。
#2
0
Arrays of references is not allowed in C++. Also there can be no pointers to references.
C ++中不允许使用引用数组。也没有指向引用的指针。