1、定义一个Box(盒子)类,数据成员包括length(长)、 width(宽)、height(高)、volume(体积),要求用构造函数对数据成员进行初始化,用成员函数disp_vol输出盒子的体积。
(1)要求用重载构造函数的方法提供2种或以上初始化数据成员length、width、height的方法;
(2)定义一个拷贝构造函数,使得可以通过一个对象(例如box1)来初始化一个新对象(例如box2),新对象的数据成员length、width、height的大小为原对象的一半。
#include using namespace std; class Box { public: Box(); Box(double l,double w,double h); Box(const Box &b); void disp_vol(); private: double length; double width; double height; double volume; }; Box::Box() { length=1.0; width=1.0; height=1.0; volume=length*width*height; } Box::Box(double length,double width,double height) { this->length=length; this->width=width; this->height=height; volume=this->length*this->width*this->height; } Box::Box(const Box &b) { length=b.length/2.0; width=b.width/2.0; height=b.height/2.0; volume=length*width*height; } void Box::disp_vol() { cout<<"the volume=" < int main() { Box box1,box2(1.0,2.0,3.0); Box box3(box2); //Box box4=box2; box1.disp_vol(); box2.disp_vol(); box3.disp_vol(); //box4.disp_vol(); system("pause"); return 0; } 2、定义一个Student类,管理一个学生的基本信息,包括学号、姓名、英语成绩等数据成员,要求用带三个参数的构造函数初始化数据成员,用3个成员函数分别修改学号、姓名、英语成绩等数据成员,用disp_stud显示学生信息。(注意在程序中体现对象的构造和析构过程)。 #include #include using namespace std; class Student { public: Student(string stu_num1,string stu_name1,float english_score1); void change_num(string num1); void change_name(string name1); void change_score(float score1); void disp_stud(); ~Student(); private: string stu_num; string stu_name; float english_score; }; Student::Student(string stu_num1,string stu_name1,float english_score1) { cout<<"construting..."< stu_name=stu_name1; english_score=english_score1; } Student::~Student() { cout<<"destruting..."< void Student::change_num(string num1) { stu_num=num1; } void Student::change_name(string name1) { stu_name=name1; } void Student::change_score(float score1) { this->english_score=score1; } void Student::disp_stud() { cout <<"学号:"< int main() { Student stu1("100200 stu1.disp_stud(); cout< stu1.change_name("张三"); stu1.change_score(60); stu1.disp_stud(); cout< system("pause"); return 0; }下载本文