{
cout<<\编号:\ cout<<\性别:\ cout<<\生日:\ birthday.display();
cout< cout<<\身份证号:\ } ~Person() //析构函数 { cout<<\号人员已经录入\ } }; int main() { Person p1; p1.input(); p1.output(); return 0; } 4-11 定义一个矩形类,有长、宽两个属性,有成员函数计算矩形的面积 解: #include public: Rectangle(float len,float wid) { length=len; width=wid; } ~Rectangle(){}; float getlen() { return length; } float getwid() { return width; } float getarea(); private: float length; float width; }; float Rectangle::getarea() { } void main() { } float length, width; cout << \请输入矩形的长度:\cin >> length; cout << \请输入矩形的宽度:\cin >> width; Rectangle r(length, width); cout << \长为\宽为\的矩形的面积为:\<< r.getarea () << endl; return length*width; 4-12 定义一个\数据类型\类,能处理包含字符型、整型、浮点型三种类型的数据, 给出其构造函数。 解: #include enum { character, integer, floating_point }vartype; union { }; char c; int i; float f; public: datatype(char ch) { vartype = character; c = ch; } datatype(int ii) { vartype = integer; i = ii; } datatype(float ff) { } void print(); vartype = floating_point; f = ff; }; void datatype::print() { switch (vartype) { case character: cout << \字符型: \ break; case integer: cout << \整型: \ break; case floating_point: cout << \浮点型: \ } break; } void main() { datatype A('c'), B(12), C(1.44F); } A.print(); B.print(); C.print(); 4-13 定义一个Circle 类,有数据成员半径Radius,成员函数GetArea(),计算圆的面积,构 造一个Circle 的对象进行测试。 解: #include public: Circle(float r) { radius=r; } float getarea(); private: }; float radius; float Circle::getarea() { } void main() { float a; } cout<<\:\cin>>a; Circle mycircle(a); cout<<\return PI*radius*radius; 4-14 定义一个tree 类,有成员ages,成员函数grow(int years)对ages 加上years,age()显示tree 对象的ages 的值。 #include class Tree { int ages; public: Tree(int n=0); ~Tree(); }; Tree::Tree(int n) { } Tree::~Tree() { } age(); ages = n; void grow(int years); void age(); void Tree::grow(int years) { ages += years; } void Tree::age() { } { Tree t(12); t.age(); t.grow(4); cout << \这棵树的年龄为\ void main() } /* 2011-10-25 provided ty Liu Hui 4-19 编写一个名为CPU的类,描述一个CPU的以下信息:时钟频率,最大不会超过3000MHz;字长,可以是32为或是64位;核数,可以是单核,双核或四核;是否支持超线程。 各信息要求使用位域来表示。通过输出sizeof(CPU)来观察该类所占的字节数。 */ #include class CPU //定义一个CPU类 { private: //CPU类的私有成员 double clockrate;//时钟频率,最大不超过3000MHz int wordsize;//字长,32或64 bit int heshu;//可单核,双核或四核 bool m;//是否支持超线程 public: CPU(double Newclockrate,int Newwordsize,int Newheshu,bool Newm) //构造函数 { clockrate=Newclockrate; wordsize=Newwordsize; heshu=Newheshu; m=Newm; //描述CPU信息的函数 } void describe(); }; void CPU::describe() //描述CPU信息的函数