无法在成员函数本身中声明派生数据类型指针变量
Not able to declare a derived datatype pointer variable in member function itself
我正在尝试创建一个函数来打印两个链表的公共元素。我将指针传递给两个列表的头部作为参数(head1 和 head2)。
我还尝试在成员函数本身中声明两个指针等于 head1 和 head2(分别为 curr1 和 curr2),这样我就可以在不更改两个列表的头指针的情况下执行所需的操作。但是我做不到。
class :
class SimilarEle {
private: struct Node {
int data;
Node* next;
};
public: Node* head = NULL;
void AddNode (int addData);
bool Common_ele (Node*head1, Node*head2);
/*
// this declaration is valid and no error.
Node* curr1 = NULL;
Node* curr2 = NULL;
*/
};
和函数
bool SimilarEle :: Common_ele(Node*head1, Node*head2) {
bool flag2 = false;
Node* curr1 = head1, curr2 = head2; //error occured by this declrn'
while (curr1 != NULL) {
while (curr2 != NULL){
if (curr1 -> data == curr2 -> data) {
cout << curr1 -> data << " ";
flag2 = true;
}
curr2 = curr2 -> next;
}
curr1 = curr1 -> next;
curr2 = head2;
}
return flag2;
}
此外,如果我在 class 本身中声明相同的指针(curr1 和 curr2),我就能够编译该程序。以下是发生的错误。
conversion from 'SimilarEle::Node' to non-scalar type 'SimilarEle::Node'
requested Node curr1 = head1, curr2 = head2;
感谢任何帮助。
它告诉你不能从一个节点*转换为一个节点。每个指针变量声明需要一个 *.
Node *curr1 = head1;
Node *curr2 = head2;
或
Node *curr1 = head1, *curr2 = head2;
当您将变量声明为
Node* curr1 = head1, curr2 = head2; //error occured by this declrn'
只有 curr1 被声明为指针类型。 curr2 实际上被声明为 Node 结果是
Node* curr1 = head1;
Node curr2 = head2;
我建议单独拼写每个变量以提高可读性。如果你真的想在一行中完成,你需要做
Node *curr1 = head1, *curr2 = head2;
我正在尝试创建一个函数来打印两个链表的公共元素。我将指针传递给两个列表的头部作为参数(head1 和 head2)。
我还尝试在成员函数本身中声明两个指针等于 head1 和 head2(分别为 curr1 和 curr2),这样我就可以在不更改两个列表的头指针的情况下执行所需的操作。但是我做不到。
class :
class SimilarEle {
private: struct Node {
int data;
Node* next;
};
public: Node* head = NULL;
void AddNode (int addData);
bool Common_ele (Node*head1, Node*head2);
/*
// this declaration is valid and no error.
Node* curr1 = NULL;
Node* curr2 = NULL;
*/
};
和函数
bool SimilarEle :: Common_ele(Node*head1, Node*head2) {
bool flag2 = false;
Node* curr1 = head1, curr2 = head2; //error occured by this declrn'
while (curr1 != NULL) {
while (curr2 != NULL){
if (curr1 -> data == curr2 -> data) {
cout << curr1 -> data << " ";
flag2 = true;
}
curr2 = curr2 -> next;
}
curr1 = curr1 -> next;
curr2 = head2;
}
return flag2;
}
此外,如果我在 class 本身中声明相同的指针(curr1 和 curr2),我就能够编译该程序。以下是发生的错误。
conversion from 'SimilarEle::Node' to non-scalar type 'SimilarEle::Node'
requested Node curr1 = head1, curr2 = head2;
感谢任何帮助。
它告诉你不能从一个节点*转换为一个节点。每个指针变量声明需要一个 *.
Node *curr1 = head1;
Node *curr2 = head2;
或
Node *curr1 = head1, *curr2 = head2;
当您将变量声明为
Node* curr1 = head1, curr2 = head2; //error occured by this declrn'
只有 curr1 被声明为指针类型。 curr2 实际上被声明为 Node 结果是
Node* curr1 = head1;
Node curr2 = head2;
我建议单独拼写每个变量以提高可读性。如果你真的想在一行中完成,你需要做
Node *curr1 = head1, *curr2 = head2;