Why scope resolution necessary for struct define i

2019-04-30 18:06发布

I have a singly linked list implementation as shown below:

Header

class SinglyLinkedList
{
  struct Node
  {
    Node * _pNext;
    int    _data;
  };

public:

  Node * SomeFun(Node * ip1, Node * ip2);  
  // Some more methods here
};

Now when implementing one of the methods of this class

CPP

Node * SinglyLinkedList::SomeFun(Node * ip1, Node * ip2)
{
  //Some code and return
}

The strange behavior I am not understanding is that when compiling, the compiler refuses to recognize the type "Node" in the return type unless I specify it as SinglyLinkedList::Node. But the same type for function arguments is recognized without specifying it explicitly.. Ideally I felt that in both cases there should be no need for this explicit specifying because Node is defined in the same class. Can anyone throw some light on this?

标签: c++ class scope
2条回答
爷的心禁止访问
2楼-- · 2019-04-30 18:52

Adding to ForEveR's answer, this issue is solved in C++11 using trailing return clauses.

// Regular return style
SinglyLinkedList::Node* SinglyLinkedList::SomeFun(Node * ip1, Node * ip2) { ... }

// Trailing return style
auto SinglyLinkedList::SomeFun(Node * ip1, Node * ip2) -> Node * { ... }

In the regular style, you have not yet entered class scope (it only begins after the qualified name of the method has ended).

In the trailing return style however, the return type is in the class scope (like the arguments) and therefore the qualification not necessary.

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-30 18:56
SinglyLinkedList::Node * SinglyLinkedList::SomeFun

Here, you are not in class-scope. But in parameters clause, or in function you are IN class-scope, so you shouln't qualify, that Node is from class SinglyLinkedList, since compiler already knows that.

n3376 3.3.7/1

The following rules describe the scope of names declared in classes.

The potential scope of a declaration that extends to or past the end of a class definition also ex- tends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, member func- tion definitions (including the member function body and any portion of the declarator part of such definitions which follows the declarator-id, including a parameter-declaration-clause and any default arguments

查看更多
登录 后发表回答