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;}
阅读全文
0 0
- 16-20.类的基本与练习。
- 栈的基本练习
- struts 的基本练习
- easyui的基本练习
- 递归的基本应用练习...
- 基本排序算法的练习
- 最基本的io练习
- 钢琴练习的基本步骤
- 容器基本练习:equals与hashCode——判定对象是否相同与哈希值的关系
- java 设计作业——学生类的基本练习
- [php学习十三]javaScript的基本练习4-与php的相互调用
- 练习-类的创建与调用
- 创建类与对象的练习
- (转)练习气功的基本方法
- C#中数据库基本操作的练习
- [php学习十]javaScript的基本练习
- 关于JSP基本语法的练习
- 一些最基本的小练习
- Jquery 选择器 几点下面的值
- 【转载修改】后期静态绑定
- git的提交原理
- Codeforces 298B Sail 题解
- Bosent基础培训手册(后台部分)
- 16-20.类的基本与练习。
- 合并排序数组
- java虚拟机内存不足
- tomcat 采用 APR apache poartable runtime
- Snort规则
- onvif协议实现1:gsoap安装
- 如何在linux嵌入式开发板上开机自动运行用户应用程序
- php常用数组函数总结版
- SpringAOP给类添加新的功能