LinkedList实现C ++错误指针间接

时间:2017-04-21 09:19:57

标签: c++

我刚刚开始使用C ++。我试图用C ++编写一个简单的LinkedList。 但是我收到以下错误,因为我无法弄清楚为什么我不能使用链接对象printAll调用成员函数*newLinkThree

main.cpp:40:16: error: member reference type 'Link *' is a pointer; maybe you
      meant to use '->'?
  *newLinkThree.printAll(newLinkThree);
   ~~~~~~~~~~~~^
               ->
main.cpp:40:3: error: indirection requires pointer operand ('void' invalid)
  *newLinkThree.printAll(newLinkThree);

这是我的代码 -

#include <iostream>

using namespace std;

class Link {
  char* value;
  Link* next;
public:

  Link(char* val, Link* nextLink) {
    value = val;
    nextLink = next;
  }

  ~Link() {
    value = NULL;
    delete[] next;
  }

  void printAll(Link* top) {
    if(top->next == NULL) {
      cout<<top->value<<endl;
      return;
    }

    cout<<top->value<<endl;
    printAll(top->next);
  }
};

int main() {

  char* first = "First";
  char* second = "Second";
  char* third = "Third";

  Link* newLink = new Link(first, NULL);
  Link* newLinkTwo = new Link(second, newLink);
  Link* newLinkThree = new Link(third, newLinkTwo);
  *newLinkThree.printAll(newLinkThree);
  return 0;

}

1 个答案:

答案 0 :(得分:1)

请注意,operator.的{​​{3}}高于operator*。所以

*newLinkThree.printAll(newLinkThree); 

相当于

*(newLinkThree.printAll(newLinkThree));

但你不能在指针上调用operator.

您可以添加括号以指定优先级:

(*newLinkThree).printAll(newLinkThree);

或正如建议的错误消息一样,

newLinkThree->printAll(newLinkThree);