/* *本例子主要是针对一个关于引用的用法 *这个用法很值得注意一下,特别是注释部分 */ #include <iostream> #include <cstdlib> using namespace std; class Tdate { public: Tdate(int m = 1, int d = 0, int y = 1995) { month = m; day = d; year = y; } //下面这些句子很牛啊,其实完全可以分开,再每个写 //一个set方法 //下面的是返回的引用,可以用作t=d.getm(); //或者是d.getm()=3;可以对这个返回的引用值进行赋值 //这样可以对私有成员进行修改 int &getm(){return month;} int &getd(){return day;} int &gety(){return year;} /* void setm(int m){month = m;} void setd(int d){day = d;} void sety(int y){year = y;} */ protected: int month; int day; int year; }; class People { private: int number; char sex; int id; Tdate birthday; public: People(int n = 0, char s = 'm', int i = 32000000, int m = 1, int d = 0, int y = 1995) :birthday(m, d, y) { number = n; sex = s; id = i; } ~People(){cout<<"析构..."<<endl;} People(People &p); void output(); void input(); }; People::People(const People &p) //注意这里的const { number = p.number; sex = p.sex; id = p.id; //下面的这个用法一定要注意!!!由于是引用所以可以直接赋值! birthday.gety() = p.birthday.gety(); birthday.getm() = p.birthday.getm(); birthday.getd() = p.birthday.getd(); /* birthday.sety(p.birthday.gety()); ... ... */ cout<<"copy..."<<endl; } void People::input() { cout<<"/n input number:"; cin>>number; cout<<"/n input sex:"; cin>>sex; cout<<"/n input id:"; cin>>id; cout<<"/n input year of birthdate:"; cin>>birthday.gety();//这个用法一定要注意!!!由于是引用所以可以直接赋值! cout<<"/n input month of birthdate:"; cin>>birthday.getm();//同上 cout<<"/n input day of birthdate:"; cin>>birthday.getd();//同上 /* int x; int y; int z; cin>>x; birthday.sety(x); cin>>y; birthday.setm(y); cin>>z; birthday.setd(z); */ } void People::output() { cout<<"the info of people:"<<endl; cout<<"number "<<number<<endl; cout<<"sex "<<sex<<endl; cout<<"id "<<id<<endl; cout<<"birthday "<<birthday.gety()<<"--" <<birthday.getm()<<"--"<<birthday.getd()<<endl; } void main() { People p1; p1.output(); p1.input(); p1.output(); People p2(p1); cout<<"another"<<endl; p2.output(); system("pause"); }