开发者

Linked List implementation with structures or class?

I am starting data开发者_如何学JAVA structures in C++ and while reading, I came up to the following snippet,

template <class Node_entry>
struct Node {
// data members
Node_entry entry;
Node<Node_entry> *next;
// constructors
Node( );
Node(Node_entry, Node<Node_entry> *link = NULL);
};

Can anyone please elaborate why the author choose a structure and not a class for the implementation of the singly linked list? Thanks.


He wanted the default access to be public - that's the only difference between classes and structures in C++


Probably because in a struct all members are public by default. In a class they are private by default.

If the author choose a class, he would've written this:

template <class Node_entry>
class Node {
public: // note this! <------------
// data members
Node_entry entry;
Node<Node_entry> *next;
// constructors
Node( );
Node(Node_entry, Node<Node_entry> *link = NULL);
};


struct and class both define classes, and can have methods, members, constructors, etc.

The only difference is that structure members are public by default, and that structures inherit publicly by default.

See this question.


By default members of a struct are public i.e. visible to everything outside them whereas members of a class are by default private. This is the only difference between the two keywords (I believe).


From algorithms and data structures point of view, there is no difference between doing it using structure or classes! Books that are talking about algorithms or data structure don't care about OOP, for example, in Introduction to Algorithms they are using pascal and sometimes pseudo code. The important thing is to deliver the idea. The author may choose to use structures because he doesn't want to bother the reader about OOP principles and best practices, he doesn't want you to say hey why he defined this field public and not private with setters and getters. by this way you are getting far from data structure and algorithms.


Probably because s/he wanted to teach algorithms and data structures, and didn't want to distract with OO design issues.


If you are doing it from algorithms and data structures point of view anything is fine but when it comes to production members of a struct are public so visible to everything outside but classes are by default private

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜