类的版式
类可以将数据和函数封装在一起,其中函数表示了类的行为(或称服务)。类提供关 键字 public、protected 和 private,分别用于声明哪些数据和函数是公有的、受保护的或 者是私有的。这样可以达到信息隐藏的目的,即让类仅仅公开必须要让外界知道的内容, 而隐藏其它一切内容。我们不可以滥用类的封装功能,不要把它当成火锅,什么东西都 往里扔。 类的版式主要有两种方式:
(1)将 private 类型的数据写在前面,而将 public 类型的函数写在后面,。 采用这种版式的程序员主张类的设计“以数据为中心”,重点关注类的内部结构。
(2)将 public 类型的函数写在前面,而将 private 类型的数据写在后面, 采用这种版式的程序员主张类的设计“以行为为中心”,重点关注的是类应该提供什么样 的接口(或服务)。 很多 C++教课书受到 Biarne Stroustrup 第一本著作的影响,不知不觉地采用了“以 数据为中心”的书写方式,并不见得有多少道理。
我建议读者采用“以行为为中心”的书写方式,即首先考虑类应该提供什么样的函 数。这是很多人的经验——“这样做不仅让自己在设计类时思路清晰,而且方便别人阅 读。因为用户最关心的是接口,谁愿意先看到一堆私有数据成员!”
1 #include <iostream> 2 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 using namespace std; 5 int main(int argc, char** argv) { 6 //用 sizeof 计算各类种常量的字节长度 7 cout<<"sizeof('$')="<<sizeof('$')<<endl; 8 cout<<"sizeof(1)="<<sizeof(1)<<endl; 9 cout<<"sizeof(1.5)="<<sizeof(1.5)<<endl; 10 cout<<"sizeof(\"Good!\")="<<sizeof("Good!")<<endl; 11 12 //用sizeof 计算各类型变量的字节长度 13 int i=100; 14 char c='A'; 15 float x=3.1416; 16 double p=0.1; 17 cout<<"sizeof(i)="<<sizeof(i)<<endl; 18 cout<<"sizeof(c)="<<sizeof(c)<<endl; 19 cout<<"sizeof(x)="<<sizeof(x)<<endl; 20 cout<<"sizeof(p)="<<sizeof(p)<<endl; 21 22 //用sizeof 计算表达式的字节长度 23 cout<<"sizeof(x+1.732)="<<sizeof(x+1.732)<<endl; 24 25 //用 sizeof 计算各类型的字节长度 26 cout<<"sizeof(char)="<<sizeof(char)<<endl; 27 cout<<"sizeof(int)="<<sizeof(int)<<endl; 28 cout<<"sizeof(float)="<<sizeof(float)<<endl; 29 cout<<"sizeof(double)="<<sizeof(double)<<endl; 30 31 //用sizeof 计算数组的字节长度 32 char str[]="This is a test."; 33 int a[10]; 34 double xy[10]; 35 cout<<"sizeof(str)="<<sizeof(str)<<endl; 36 cout<<"sizeof(a)="<<sizeof(a)<<endl; 37 cout<<"sizeof(xy)="<<sizeof(xy)<<endl; 38 39 //用sizeof 计算自定义类型的长度 40 struct st { 41 short num; 42 float math_grade; 43 float Chinese_grade; 44 float sum_grade; 45 }; 46 st student1; 47 cout<<"sizeof(st)="<<sizeof(st)<<endl; 48 cout<<"sizeof(student1)="<<sizeof(student1)<<endl; 49 return 0; 50 }