簡體   English   中英

指向指針 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++ 中指向指針的指針是什么。

回到第一任校長。 什么是變量? 變量是特定類型存儲

對變量有哪些可用的操作? 它們可以被讀取寫入或者它們的地址可以被獲取

取地址運算符&的結果是什么? 指向變量的指針。

什么是指針? 表示變量

可以對指針值進行哪些操作? 可以使用*取消引用指針。 這樣做會產生一個變量 (在指針上還有其他可用的操作,但我們不用擔心這些。)

所以讓我們總結一下。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM