是否可以使用带有指针运算符的引用类型别名来声明对指针的引用?
Is it possible to use reference type alias with pointer operator to declare a reference to pointer?
我这里有一个简单的例子:我使用 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
}
因为出于好奇,当我使用 std::vector<int>::reference
的元素类型时,我想将它与指针运算符 *
结合起来以声明对指针的引用:
int* ptr = new int(1000);
std::vector<int>::*(reference rptr) = ptr; // error: expected expression
但我可以使用指针类型别名结合引用运算符“&”来声明它:
using pInt = int*;
int i = 57;
int* ptrI = &i;
pInt(&rpInt) = ptrI;
cout << *rpInt << endl;
** 我知道我不能有一个指向引用的指针,因为引用只是一个已经存在的对象的别名,而指针是一个对象,因此我们可以有一个指针或对它的引用。
在 C++ 中不能有指向引用的指针。在 C++ 中,引用只是它们所引用事物的别名,标准甚至不要求它们占用任何存储空间。尝试使用引用别名来引用指针是行不通的,因为使用别名只会给你一个指向引用类型的指针。
因此,如果您想要一个指向引用所指事物的指针,您只需使用
auto * ptr = &reference_to_thing;
如果你想引用一个指针,语法是
int foo = 42;
int* ptr = &foo;
int*& ptr_ref = ptr;
我这里有一个简单的例子:我使用 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
}
因为出于好奇,当我使用
std::vector<int>::reference
的元素类型时,我想将它与指针运算符*
结合起来以声明对指针的引用:int* ptr = new int(1000); std::vector<int>::*(reference rptr) = ptr; // error: expected expression
但我可以使用指针类型别名结合引用运算符“&”来声明它:
using pInt = int*; int i = 57; int* ptrI = &i; pInt(&rpInt) = ptrI; cout << *rpInt << endl;
** 我知道我不能有一个指向引用的指针,因为引用只是一个已经存在的对象的别名,而指针是一个对象,因此我们可以有一个指针或对它的引用。
在 C++ 中不能有指向引用的指针。在 C++ 中,引用只是它们所引用事物的别名,标准甚至不要求它们占用任何存储空间。尝试使用引用别名来引用指针是行不通的,因为使用别名只会给你一个指向引用类型的指针。
因此,如果您想要一个指向引用所指事物的指针,您只需使用
auto * ptr = &reference_to_thing;
如果你想引用一个指针,语法是
int foo = 42;
int* ptr = &foo;
int*& ptr_ref = ptr;