Node class 是linked list implementations 的一部分。 Linked list是由node类的节点对象组成的。 这些node 封装了一些数据信息, 例如当节点表示存储的个人信息的时候, 这些数据可能有人名, 邮箱, 地址, 年龄等等。
node有一个指向下一个node 的指针。 利用这个指针, 我们将节点串成一个linked list的数据结构。 下面首先以一个例子谈谈如何实现一个node class:
/*
* Contact.h
*
* Created on: Jul 6, 2014
* Author: ***
*
*
*/
#ifndef CONTACT_H
#define CONTACT_H
#include <iostream>
#include <string>
class Contact {
friend std::ostream& operator<<(std::ostream& os, const Contact& c);
public: //public area
Contact(std::string n = "none"); // constructor with default parameter
private: //private area
//you can add information like email address, phone number etc.
std::string name;
Contact* next;//linked pointer so it can be linked to the next node in the linked list
};
#endif // end of CONTACT_H
Contact.cpp 是上述头文件的实现文件, 如下:
/*
* Contact.h
*
* Created on: Jul 6, 2014
* Author: ***
*
*
*/
#ifndef CONTACT_H
#define CONTACT_H
#include <iostream>
#include <string>
class Contact {
friend std::ostream& operator<<(std::ostream& os, const Contact& c);
public: //public area
Contact(std::string n = "none"); // constructor with default parameter
private: //private area
//you can add information like email address, phone number etc.
std::string name;
Contact* next;//linked pointer so it can be linked to the next node in the linked list
};
#endif // end of CONTACT_H
运行结果如下(在最新版本的code::blocks下(2013), 编译器必须使用gcc,而且先修改compiler, 指令为settings -> compiler and debugger, 设置为默认, 如果使用VC6.0编译器, 那么友元函数无法直接存取该类的私有成员变量, 显然不符合C++ 的现行标准, 可以理解为VC的bug):