[英]Pointer to pointer C++
我真的无法理解 C++ 中指向指针的指针是什么。 假设我有一个定义如下的类:
class Vector3
{
public:
float x,y,z;
//some constructors and methods
}
现在如果我有类似的东西怎么办
Vector3 **myVector3;
这在某种程度上 C# 相当于说List<List<Vector3> myVector3
吗? 无论如何,我如何动态分配这个 myVector3 对象? 谢谢。
这在某种程度上 C# 相当于说
List<List<Vector3> myVector3
吗?
不。
无论如何,我如何动态分配这个
myVector3
对象?
我不明白这个问题。
我真的无法理解 C++ 中指向指针的指针是什么。
回到第一任校长。 什么是变量? 变量是特定类型值的存储。
对变量有哪些可用的操作? 它们可以被读取、写入或者它们的地址可以被获取。
取地址运算符&
的结果是什么? 指向变量的指针。
什么是指针? 表示变量的值。
可以对指针值进行哪些操作? 可以使用*
取消引用指针。 这样做会产生一个变量。 (在指针上还有其他可用的操作,但我们不用担心这些。)
所以让我们总结一下。
Foo foo;
是Foo
类型的变量。 它可以包含一个Foo
。
&foo
是一个指针。 这是一个价值。 当取消引用时,它会产生变量foo
:
Foo foo;
Foo *pfoo = &foo;
*pfoo = whatever; // same as foo = whatever
pfoo
是一个变量。 一个变量可能有它的地址:
Foo **ppfoo = &pfoo;
*ppfoo = null; // Same as pfoo = null. Not the same as foo = null.
所以你去。 ppfoo
是一个变量。 它包含一个值。 它的值是一个指针。 当该指针被取消引用时,它会产生一个变量。 该变量包含一个值。 该值是一个指针。 当它被取消引用时,它会产生一个变量。 该变量的类型为Foo
。
确保这在您的脑海中非常清楚。 当你感到困惑时,回到首要原则。 指针是值,它们可能会被取消引用,这样做会产生一个变量。 一切都源于此。
List 的 C++ 等价物将是 std::vector。 别介意你的类被称为向量; 这是一个向量,就像在类似类型对象的动态可扩展序列中一样。
如果你想要一个 C++ 中 Vector3 的列表,你想要
std::vector<std::vector<Vector3> myVectorVectorVictor;
这也分配了一个。 不需要指针。
Vector3 **myVector3;
基本上只是一个指向另一个指针的指针。 取消引用它会给你一个指向Vector3
的指针。
例子 :
#include <iostream>
class Vector3
{
public:
float x, y, z;
//some constructors and methods
};
int main()
{
Vector3 **myVector3 = new Vector3*[50]; // allocate 50 Vector3 pointers and set myVector3 to the first, these are only pointers, pointing to nothing.
//myVector3[0]->x; myVector3[0] is a Vector3 pointer, currently pointing to nothing dereferencing this will result in Undefined Behaviour
myVector3[0] = new Vector3; // allocate a Vector3 on the heap and let pointer 1 ( of the 50 ) point to this newly allocated object.
myVector3[0]->x = 5;
std::cout << "myVector3[0]->x : " << myVector3[0]->x; // prints "myVector3[0]->x : 5"
std::cin.get();
}
你可以这样做:
Vector3 * pointer = new Vector3; // points to a instance of Vector3 on the heap
Vector3 * * pointerToPointer = & pointer; // points to pointer; we take the address of pointer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.