[英]Not able to declare a derived datatype pointer variable in member function itself
我正在尝试创建一个函数,该函数将打印两个链表的常见元素。 我将两个列表的开头的指针作为参数(head1和head2)传递。
我还尝试在成员函数本身中声明等于head1和head2的两个指针(分别为curr1和curr2),以便我可以执行所需的操作,而无需更改两个列表的head指针。 但是我无法做到这一点。
类:
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;
}
此外,如果我在类本身中声明相同的指针(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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.