如果不得已需要全局变量,则使全局变量加前缀 g_(表示 global)。

例如: int g_howManyPeople; // 全局变量 int g_howMuchMoney; // 全局变量

 #include <iostream>
#include<string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std;
//定义双亲(parent)类
class parent {
char f_name[];
char m_name[];
char tel[];
public:
// parent类的构造函数,其带有缺省值
parent(char *p1="",char *p2="",char *p3="") {
strcpy(f_name,p1);
strcpy(m_name,p2);
strcpy(tel,p3);
}
//显示parent对象的数据
show_parent(void) {
cout<<"The parent:"<<endl;
cout<<" father's name:"<<f_name<<endl;
cout<<" mother's name:"<<m_name<<endl;
cout<<" tel:"<<tel<<endl;
}
};
//定义student类
class student {
int num;
char name[];
float grade;
parent pt;
public:
// student类的构造函数
student(int n,char *str,float g,class parent t) {
num=n;
strcpy(name,str);
grade=g;
pt=t;
}
//显示student对象的数据
show_student(void) {
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"grade:"<<grade<<endl;
pt.show_parent();
}
};
//main()函数测试student类的对象
int main(int argc, char** argv) {
//创建双亲对象
parent p1("ZhangHua","LiLan",""); //创建学生对象
student st(,"ZhangHui",91.5,p1); //显示学生信息
cout<<"p1:"<<endl;
p1.show_parent(); //显示学生信息
cout<<"st:"<<endl;
st.show_student();
return ;
}
05-12 00:32