无法在成员函数本身中声明派生的数据类型指针变量

时间:2018-09-11 15:22:30

标签: c++ class variable-declaration

我正在尝试创建一个函数,该函数将打印两个链表的常见元素。我将两个列表的开头的指针作为参数(head1和head2)传递。

我还尝试在成员函数本身中声明两个分别等于head1和head2的指针(分别为curr1和curr2),以便我可以执行所需的操作而无需更改两个列表的head指针。但是我无法做到这一点。

class:

Customer    A   B   C   D   E   F   G   H   I   J   Customers_live_consecutive_months
11/30/2015  1   0   1   0   0   1   1   0   0   0   0
12/31/2015  0   1   0   1   0   1   1   0   0   1   2
1/31/2016   0   0   0   0   0   1   1   0   0   1   3
2/29/2016   1   1   1   1   1   1   0   1   1   1   2
3/31/2016   1   1   0   1   1   0   1   1   0   1   6
4/30/2016   0   1   1   1   0   1   1   1   0   1   5
5/31/2016   1   1   1   1   1   1   0   1   0   1   6

和功能

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;
           */
 };

此外,如果我在类本身中声明了相同的指针(curr1和curr2),则可以编译程序。以下是发生的错误。

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;
    }

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

它告诉您不能从节点*转换为节点。每个指针变量声明都需要一个*。

Node  *curr1 = head1;
Node  *curr2 = head2;

OR

Node  *curr1 = head1, *curr2 = head2;

答案 1 :(得分:1)

将变量声明为

Node* curr1 = head1, curr2 = head2;    //error occured by this declrn'

只有curr1被声明为指针类型。实际上,curr2被声明为Node,结果为

Node* curr1 = head1; 
Node curr2 = head2; 

我建议分别拼出每个变量以提高可读性。如果您确实想一行完成,则需要

Node *curr1 = head1, *curr2 = head2;