g ++返回错误,当我尝试使用指针的别名
问题描述:
我试图创建一个变量是一个节点指针的别名。g ++返回错误,当我尝试使用指针的别名
到目前为止,我曾尝试以下语法:
node* _p = &p;
&
node* &_p = p;
每当我试图调用一个类功能(即_p->的GetData())或甚至参考使用别名(如果(_p == NULL))我得到一个错误,指出:
error: expected primary-expression before ‘;’ token
node* newnode = _p;
我hav当我打电话时,e也尝试在_p之前放置*或&,但它没有帮助。
注:我用G ++
一个最小的,完整的,并且可验证的例子(我认为)编译:列表类的插入函数内发生 的错误...
class node{
private:
int data;
node* next;
int mark;
public:
node(int d = 0, node* n = NULL){
data = d;
next = n;
mark = 0;
}
int getdata(){return data;}
node* getnext(){return next;}
int getmark(){return mark;}
void setdata(int x){data = x;}
void setnext(node* x){next = x;}
void setmark(int x){mark = x;}
};
class list{
private:
node* L1; //head pointers to list1, list2, and freelist.
node* L2;
node* free;
node* front;
public:
list(){
front = new node(); //generate free list (empty)
free = front;
L1 = NULL;
L2 = NULL;
node* p = free;
for (int i = 1; i < 10; i++){
p -> setnext(new node());
p = p -> getnext();
}
delete p;
}
void insert(int a, int x){
if (free == NULL) {
cout << a << " is full. can't insert " << x << " into the list." << endl;
return;
}
if (a == 1) node* &list = L1;
else if (a == 2) node* &list = L2;
else {
cout << "not a valid list";
return;
}
if (list == NULL){
list = free;
free = free -> getnext();
list -> setdata(x);
list -> setnext(NULL);
}
else {
node* p = list;
while (p -> getnext() != NULL) {p = p -> getnext();}
p -> setnext(free);
free = free -> getnext();
p -> getnext() -> setnext(NULL);
p -> getnext() -> setdata(x);
}
}
};
答
在
if (a == 1) node* &list = L1;
else if (a == 2) node* &list = L2;
list
在if
和else if
内作用域。它在其他地方不存在。下面是用大括号的代码,以使问题更加明显:
if (a == 1)
{
node* &list = L1;
}
else if (a == 2)
{
node* &list = L2;
}
由于定只能在初始化坐下,你将不得不在其他地方移动的逻辑。你的代码的结构并不容易。
幸运的是,您似乎并不需要这个参考。在这里使用常规指针。
node* list;
if (a == 1) list = L1;
else if (a == 2) list = L2;
编辑
正如在评论中指出离退休忍者,list
不需要做个参考。在这种情况下,我们曾经用一个函数来选择正确的名单,以照顾唯一能够座位参考的问题:
node* & getList(int a)
{
if (a == 1)
{
return L1;
}
else if (a == 2)
{
return L2;
}
else
{
throw std::runtime_error("not a valid list");
}
}
注扔在失败的例外。最好在insert
以下的某处处理,因为insert
无法正确处理它。
修订后的初始化看起来像
node* &list = getList(a);
现在list
由函数范围的,坐在只有一次,仍然是一个参考。
请提*生此错误的[mcve]。 – chris
如果'p'是指向'node'的指针,请尝试'node * _p = p;' – Knoep
node *&list = L1; list = list-> getnext(); 第二行是我的实际代码chris的一个例子。 – ggkfox