标识符的长度应当符合“min-length && max-information”原则

标识符的长度应当符合“min-length && max-information”原则。 几十年前老 ANSI C 规定名字不准超过 6 个字符,现今的 C++/C 不再有此限制。一 般来说,长名字能更好地表达含义,所以函数名、变量名、类名长达十几个字符不足为 怪。

那么名字是否越长约好?不见得! 例如变量名 maxval 就比 maxValueUntilOverflow 好用。

单字符的名字也是有用的,常见的如 i,j,k,m,n,x,y,z 等,它们通常可用作函数 内的局部变量。

 1 #include <iostream>
 2 
 3 using namespace std;
 4 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 5 const int MAX=5;       //假定栈中最多保存5个数据
 6 //定义名为stack的具有栈功能的类
 7 class  stack {
 8     //数据成员
 9     float  num[MAX];     //存放栈数据的数组
10     int  top;             //指示栈顶位置的变量
11 public:
12     //成员函数
13     stack(char c)          //初始化函数
14     {
15         top=0; 
16         cout<<"Stack "<<c<<" initialized."<<endl;
17     }     
18     void push(float x)      //入栈函数
19     {
20         if (top==MAX){
21             cout<<"Stack is full !"<<endl;
22             return;
23         };
24         num[top]=x;
25         top++;
26     }
27     float pop(void)           //出栈函数
28     {
29         top--;
30         if (top<0){
31         cout<<"Stack is underflow !"<<endl;
32         return 0;
33         };
34         return num[top];
35     }
36 };
37 
38 int main(int argc, char** argv) {
39         //声明变量和对象
40     int i;
41     float x;
42     stack a('a'),b('b');    //声明(创建)栈对象并初始化
43 
44     //以下利用循环和push()成员函数将2,4,6,8,10依次入a栈
45     for (i=1; i<=MAX; i++)
46         a.push(2.0*i);
47 
48     //以下利用循环和pop()成员函数依次弹出a栈中的数据并显示
49     for (i=1; i<=MAX; i++)
50        cout<<a.pop()<<"  ";
51     cout<<endl;
52     return 0;
53 }
原文地址:https://www.cnblogs.com/borter/p/9413390.html