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

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

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

 1 #include <iostream>
 2 #include<string.h>
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 
 5 using namespace std;
 6 //定义双亲(parent)类
 7 class parent {
 8     char  f_name[20];
 9     char  m_name[20];
10     char  tel[10];
11 public:
12     // parent类的构造函数,其带有缺省值
13     parent(char *p1="",char *p2="",char *p3="") {
14         strcpy(f_name,p1);
15         strcpy(m_name,p2);
16         strcpy(tel,p3);
17     }
18     //显示parent对象的数据
19     show_parent(void) {    
20         cout<<"The parent:"<<endl;
21         cout<<"    father's name:"<<f_name<<endl;
22         cout<<"    mother's name:"<<m_name<<endl;
23         cout<<"    tel:"<<tel<<endl;
24     }
25 };
26 //定义student类
27 class student {
28     int       num;
29     char      name[20];
30     float     grade;
31     parent    pt;      
32 public:
33     // student类的构造函数
34     student(int n,char *str,float g,class parent t) {
35         num=n;
36         strcpy(name,str);
37         grade=g;
38         pt=t;
39     }
40     //显示student对象的数据
41     show_student(void) {
42         cout<<"num:"<<num<<endl;
43         cout<<"name:"<<name<<endl;
44         cout<<"grade:"<<grade<<endl;
45         pt.show_parent();
46     }
47 };
48 //main()函数测试student类的对象
49 int main(int argc, char** argv) {
50         //创建双亲对象
51     parent p1("ZhangHua","LiLan","83665215");
52 
53     //创建学生对象
54     student st(10001,"ZhangHui",91.5,p1); 
55     
56     //显示学生信息
57     cout<<"p1:"<<endl;
58     p1.show_parent();
59 
60     //显示学生信息
61     cout<<"st:"<<endl;
62     st.show_student();
63     return 0;
64 }
原文地址:https://www.cnblogs.com/borter/p/9413439.html