[英]Passing derived class pointer to function expecting base pointer by reference
[英]Passing a pointer by reference using accessor function in a class
使用訪問器函數,我試圖通過引用將指針傳遞給另一個函數。
該指針是Skiplist類的私有成員,並指向yup跳過列表的頭部。
我需要通過引用將該頭指針傳遞給insert函數,以便在需要時可以更改頭指針指向的內容。
我可以看到我的訪問器函數正在返回存儲在head中的地址,而不是head本身的地址,但是我無法確定如何解決此問題。
我得到的錯誤是這樣的:
pointer.cpp: In function 'int main()':
pointer.cpp:32:29: error: no matching function for call to 'Skiplist::insert(Nod
e*)'
test.insert(test.get_head());
^
pointer.cpp:32:29: note: candidate is:
pointer.cpp:17:8: note: void Skiplist::insert(Node*&)
void insert(Node *&head);
^
pointer.cpp:17:8: note: no known conversion for argument 1 from 'Node*' to 'No
de*&'
這是一個非常精簡的代碼版本:
#include <iostream>
using namespace std;
class Node
{
public:
private:
};
class Skiplist
{
public:
void insert(Node *&head);
Node *get_head() const;
private:
int level_count;
Node *head;
};
int main()
{
Skiplist test;
test.insert(test.get_head());
return 0;
}
Node *Skiplist::get_head() const
{
return head;
}
void Skiplist::insert(Node *&head)
{
//bla bla bla
}
Skiplist::get_head()
應該返回Node *&
以返回引用。 並且由於您要允許它修改head
,所以您不能聲明成員函數const
。
#include <iostream>
using namespace std;
class Node
{
public:
private:
};
class Skiplist
{
public:
void insert(Node *& head);
Node *&get_head();
private:
int level_count;
Node *head;
};
int main()
{
Skiplist test;
test.insert(test.get_head());
return 0;
}
Node *&Skiplist::get_head()
{
return head;
}
void Skiplist::insert(Node *&head)
{
//bla bla bla
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.