簡體   English   中英

返回指向C ++中對象的指針

[英]Return a pointer to pointer to object in C++

我正在嘗試定義一組模板類來表示C ++中的搜索樹。
find方法中,我需要返回包含給定鍵的節點的指針(表示為指針)。 這樣,我將重用find方法來實現插入和刪除。

template <class K, class R>
struct Node {
    K key;
    R record;

    inline Node(K k, R r) {
        this->key = k;
        this->record = r;
    }
};

template <class K, class R>
struct BST_Node : public Node<K,R> {
    BST_Node<K,R> *sx;
    BST_Node<K,R> *dx;

    inline BST_Node(K key, R record)
    : Node<K,R>(key, record) {
        this->sx = NULL;
        this->dx = NULL;
    }

    BST_Node<K,R> **find(K k) {
        BST_Node<K,R> **p = k < this->key ? &this->sx : &this->dx;

        while (*p && k != (*p)->key)
             p = k < (*p)->key ? &(*p)->sx : &(*p)->dx;

        return p;
    }
/* other methods */
};

只是有一個問題:如果密鑰在根中怎么辦?
我不能因為這個而返回&this,那我該怎么辦?

因為我要使用指向指針的原因,是因為這樣可以返回NULL指針的地址,因此對於插入,我可以編寫如下內容:

BST_Node<K,R> *insert(K k, R r) {
    BST_Node<K,R> **p = this->find(k);

    if (*p == NULL) //if the search fails
        *p = new BST_Node<K,R>(k, r);

    return *p;
}

您不清楚。 在你的情況, 這種指針有型

BST_Node<K,R>* const

這意味着您無法更改方向(我不知道如何具體描述它,例如指針所指示的地址。)。 如果你回來

//BST_Node<K,R>**
return &this;

這意味着您可以通過返回值更改值。 這是不允許的。 因此發生錯誤。

為什么要在這里返回雙指針?

我看到了您的版本,並且我想您可以在函數find()中返回NULL,以指示您在根目錄下找到了密鑰。 當您編寫遞歸查找函數時,它會有些復雜,但是由於您使用的是循環,因此您只需在查找函數的第一位添加if語句即可。 insert函數中這樣寫:

if (p == NULL) //if returns the root
    /*do sth.*/

只是一個提示,我永遠不會在根目錄保存任何數據,通常,當我使用樹時,我的樹根的壽命將與樹一樣長。

我認為您應該更仔細地閱讀說明。

問題是&this位於內存中的某個位置,它指向當前對象“您所在的位置”(代碼正在執行的當前對象作用域)。
返回&this每次都指向您代碼所在的當前對象,這不是您想要的(實際上取決於編譯器,在這種情況下,我從不讀取編譯器的任何“承諾”來返回任何值,它不在C ++標准中)

解決方案很簡單:

void* tothis = malloc(sizeof(void*)); // allocate memory that will survive leaving the current scope
tothis=this; // copy the current object memory address to the object
return &tothis; // return what you want

請不要忘記稍后釋放此內存的地址(這樣就不會泄漏)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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