C++编程之约定俗成的习惯(1)
说明:C++的类定义中,可以任意安排成员函数和成员变量的位置,一般我们将成员变量都设置成私有的,而将大多成员函数都设置为公有的。其中,公有成员和私有成员顺序的安排没有统一的标准,但是我们倾向于将成员函数放在成员变量之前。
代码示例:
//包含一个非常简单的类的演示程序 //类DayOfYear #include<iostream> #include<cstdlib> using namespace std; class DayOfYear { public: void input(); void output(); void set(int newMonth,int newDay); //前提条件:newMonth和newDay可以构成一个合法的日期 void set(int newMonth); //前提条件:1<=newMonth<=12 //运行结果: 日期被设定为参数给定月份的第一天 int geyMonthNumber(); int getDay(); private: int month; int day; }; int main() { DayOfYear today,bachBirthday; cout<<"Enter today's date:\n"; today.input(); cout<<"Today's date is "; today.output(); cout<<endl; bachBirthday.set(3,21); cout<<"J.S Bach's birthday is "; bachBirthday.output(); cout<<endl; if(today.geyMonthNumber()==bachBirthday.geyMonthNumber()&&today.getDay()==bachBirthday.getDay()) { cout<<"Happy Birthday Johann Sebastian!\n"; } else { cout<<"Happy Unbirthday Johann Sebastian!\n"; } return 0; } //使用iostream和cstdlib void DayOfYear::set(int newMonth,int newDay) { if((newMonth>=1)&&(newMonth<=12)) { month=newMonth; } else { cout<<"Illegal month value!Program aborted.\n"; exit(1); } if((newDay>=1)&&(newDay<=31)) { day=newDay; } else { cout<<"Illegal day value!Program aborted.\n"; exit(1); } } void DayOfYear::set(int newMonth) { if((newMonth>=1)&&(newMonth<=12)) { month=newMonth; } else { cout<<"Illegal month value!Program aborted.\n"; exit(1); } day=1; } int DayOfYear::geyMonthNumber() { return month; } int DayOfYear::getDay() { return day; } void DayOfYear::input() { cout<<"Enter the month as a number:"; cin>>month; cout<<"Enter the day of the month:"; cin>>day; if((month<1)||(month>12)||(day<1)||(day>31)) { cout<<"Illegal date!Program aborted.\n"; exit(1); } } void DayOfYear::output() { switch(month) { case 1: cout<<"January "; break; case 2: cout<<"February "; break; case 3: cout<<"March "; break; case 4: cout<<"April "; break; case 5: cout<<"May "; break; case 6: cout<<"June "; break; case 7: cout<<"July "; break; case 8: cout<<"August "; break; case 9: cout<<"September "; break; case 10: cout<<"October "; break; case 11: cout<<"November "; break; case 12: cout<<"Decemebr "; break; default: cout<<"Error in DayOfYear::output."; } cout<<day; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
posted on 2015-04-02 07:52 Tob__yuhong 阅读(192) 评论(0) 编辑 收藏 举报