2016-07-16 44 views
0

使用访问函数,我试图通过引用传递指针到另一个函数。使用访问器函数在类中引用传递指针

该指针是班级跳过列表的私人成员,并指向a,yup,skip列表的头部。

我需要通过引用将这个头指针传递给插入函数,以便我可以在需要时更改头指针指向的内容。

我可以看到,我的存取函数正在返回存储在头部的地址,而不是头部本身的地址,但我不能为我的生活计算如何解决这个问题。

我得到的错误是这样的:

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 
} 
+0

'get_head'返回一个指针,而不是对指针的引用。 – Barmar

+0

'get_head()'返回值,这将是一个临时的,不能绑定到非常量的左值引用。 – songyuanyao

回答

1

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 
} 
+0

得到cha。非常感谢! –

相关问题