C++语言程序设计

在C++中，有一个类机制允许指定一个独立的对象集合，该对象集合由组成该类的对象以及这些对象所允许的操作组成。让我们来修改一下这个程序的最初版本，用类（class）来代替结构，看一看类是如何运作的：

| 例10-4

#include <iostream.h>
class family
{
private:
char *husband;
char *wife;
char *son;
char *daughter;
family *ptr; //ptr在类family内部声明
public:
void initialize(void);
void output(family *ptr);
};
//Anderson是类family的对象
family Anderson;
//initialize被类名限定
void family::initialize(void)
{
Anderson.ptr = &Anderson;
Anderson.ptr->husband = "John Anderson";
Anderson.ptr->wife = "Mary Anderson";
Anderson.ptr->son = "Joey Anderson";
Anderson.ptr->daughter = "Marla Anderson";
Anderson.output(Anderson.ptr);
}
//output被类名限定
void family::output(family *ptr)
{
cout<<"husband is "<<ptr->husband<<endl
<<"wife is "<<ptr->wife<<endl
<<"son is "<<ptr->son<<endl
<<"daughter is "<<ptr->daughter<<endl;
}
void main(void)
{
//initialize被对象名限定
//注意圆点（.）操作符
Anderson.initialize();
}

该程序产生如下输出结果：
husband is Mark Anderson
wife is Jennifer Anderson
son is Michael Anderson
daughter is Maria Anderson