指向指针C++的指针
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++中的指针对指针是什么。
回到第一个主体。什么是变量?对于特定类型的值,变量是存储。
对变量有哪些操作可用?它们可以从读取,将写入,也可以取其地址。
地址获取运算符&
的结果是什么?指向变量的指针。
什么是指针?表示变量的值。
指针值有哪些操作可用?可以使用*
来取消引用指针。这样做会产生一个变量。(指针上还有其他操作,但我们不要担心。)
所以让我们总结一下。
CCD_ 6是CCD_ 7类型的变量。它可以包含一个Foo
。
&foo
是一个指针。这是一种价值。当取消引用时,它产生变量foo
:
Foo foo;
Foo *pfoo = &foo;
*pfoo = whatever; // same as foo = whatever
CCD_ 11是一个变量。变量的地址可能被占用:
Foo **ppfoo = &pfoo;
*ppfoo = null; // Same as pfoo = null. Not the same as foo = null.
好了。CCD_ 12是一个变量。它包含一个值。它的值是一个指针。当该指针被取消引用时,它会生成一个变量。该变量包含一个值。该值是一个指针。当它被取消引用时,它会产生一个变量。该变量的类型为Foo
。
请确保这一点在你的脑海中非常清晰。当您感到困惑时,返回第一原则。指针是值,它们可能被取消引用,这样做会产生一个变量。一切都源于此。
List的C++等价物是std::vector。不要介意你的类被称为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
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错