문제

I want to do something like

int &a = *(new int[10]);
// access all the indices from this reference somehow.

All I can do is something like,

int *b = &a;
b[1] = 10;

Can I do it using reference? If no, why?

도움이 되었습니까?

해결책

You have to use pointers because the array index operator in C++ is only defined for pointers (and user defined classes that overloaded that operator). However the pointer can simply be a temporary:

(&a)[1] = 10;

If you want to avoid pointers then you can simply use std::array or std::vector instead:

std::array<int, 10> a;
a[1] = 10;

std::vector<int> v(n);
v[1] = 10;

다른 팁

Yes, you can certainly do so, but it goes against the grain: References are not expected to be used for getting other elements of an array but the referenced element. Please refrain.

You can use a reference:

int (&a)[10] = (int (&)[10])*new int[10];

That said, you still need to delete[] &a, and if you know the array size and it's not humongous you can just create a normal stack-based array. You can't create a reference to an array of unknown/runtime-determined length. Given you can also index pointers, this is of extremely limited practical use (mainly for passing the array to templates that themselves bind references to it, normally so they can implicitly access the array size).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top