16-20.类的基本与练习。

来源:互联网 发布:手机怎么改淘宝店铺名 编辑:程序博客网 时间:2024/06/05 06:08

1.类的定义

class Box{   public:      double length;   // 盒子的长度      double breadth;  // 盒子的宽度      double height;   // 盒子的高度};

定义一个类相当于创造了一个新的物品,而我们可以在其基础上产生单独的个体,就是对象。

2.定义对象与访问数据成员

#include <iostream> using namespace std; class Box{   public:      double length;   // 长度      double breadth;  // 宽度      double height;   // 高度}; int main( ){   Box Box1;        // 声明 Box1,类型为 Box   Box Box2;        // 声明 Box2,类型为 Box   double volume = 0.0;     // 用于存储体积    // box 1 详述   Box1.height = 5.0;    Box1.length = 6.0;    Box1.breadth = 7.0;    // box 2 详述   Box2.height = 10.0;   Box2.length = 12.0;   Box2.breadth = 13.0;    // box 1 的体积   volume = Box1.height * Box1.length * Box1.breadth;   cout << "Box1 的体积:" << volume <<endl;    // box 2 的体积   volume = Box2.height * Box2.length * Box2.breadth;   cout << "Box2 的体积:" << volume <<endl;   return 0;}

3.构造函数与析构函数

#include <iostream> using namespace std; class Line{   public:      void setLength( double len );      double getLength( void );      Line();   // 这是构造函数声明      ~Line();  // 这是析构函数声明    private:      double length;}; // 成员函数定义,包括构造函数Line::Line(void){    cout << "Object is being created" << endl;}Line::~Line(void){    cout << "Object is being deleted" << endl;} void Line::setLength( double len ){    length = len;} double Line::getLength( void ){    return length;}// 程序的主函数int main( ){   Line line;    // 设置长度   line.setLength(6.0);    cout << "Length of line : " << line.getLength() <<endl;    return 0;}

构造函数在新建类的对象时执行,析构函数在删除对象时执行。


4.个人练习


     

#include <iostream>#include<string.h>using namespace std;class ROBOT{public :        char* codename;        int damage(void);        int attack_point,deffence_point;        void attack_begin(int atk);        int attack_done(void);        void deffence_begin(int def);        int deffence_done(void);        ROBOT();        ~ROBOT();};void ROBOT::attack_begin(int atk){    attack_point = atk;}int ROBOT::attack_done(void){    return attack_point;}void ROBOT::deffence_begin(int def){   deffence_point = def;}int ROBOT::deffence_done(void){    return deffence_point;}int ROBOT::damage(void){   return  attack_point-deffence_point;}ROBOT::ROBOT(void){    cout<<"Welcome to robots war I"<<endl;}ROBOT::~ROBOT(void){    cout<<"Mission compelete!!"<<endl;}int main(int argc, char *argv[]){    ROBOT robot1;    robot1.attack_begin(1000);    robot1.deffence_begin(500);    cout<<"Attack!!"<<robot1.attack_done()<<endl;    cout<<"Damage:"<<robot1.damage()<<endl;}