Mae*_*tro 13 c++ pointers reference type-alias
我在这里有一个简单的示例:我使用类型别名using using关键字作为引用类型,然后我想知道是否可以通过指针运算符(*)使用该类型别名来声明对指针的引用:
int main(){
using ref_int = int&;
int x = 10;
int* p = &x;
//int*(&rpx) = p;
//ref_int * rptrx = p; // pointer to reference is not allowed.
*ref_int(rptrx) = p; // rptrx is undefined
}
Run Code Online (Sandbox Code Playgroud)
因为出于好奇,当我使用Element的类型时,std::vector<int>::reference我想将其与指针运算符结合*以声明对指针的引用:
int* ptr = new int(1000);
std::vector<int>::*(reference rptr) = ptr; // error: expected expression
Run Code Online (Sandbox Code Playgroud)但是我可以结合使用指针类型别名和引用运算符“&”来声明它:
using pInt = int*;
int i = 57;
int* ptrI = &i;
pInt(&rpInt) = ptrI;
cout << *rpInt << endl;
Run Code Online (Sandbox Code Playgroud)**我知道我没有指向引用的指针,因为引用只是已有对象的别名,而指针是一个对象,因此我们可以有一个指向它的指针或引用。
Nat*_*ica 14
您不能使用C ++中的引用指针。在C ++中,引用只是它们所引用对象的别名,该标准甚至不要求它们占用任何存储空间。尝试使用引用别名对指针进行引用将不起作用,因为使用别名只会给您指向引用类型的指针。
因此,如果您想要一个指向引用所指事物的指针,则只需使用
auto * ptr = &reference_to_thing;
Run Code Online (Sandbox Code Playgroud)
如果要引用指针,则语法为
int foo = 42;
int* ptr = &foo;
int*& ptr_ref = ptr;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |