首页 > 编程语言 > 详细

C++继承

时间:2014-08-16 13:53:50      阅读:211      评论:0      收藏:0      [点我收藏+]

C++继承和java中的差不多,下面举个简单示例:

main.cpp:

#include <iostream>
#include "Box.h"
#include "Carton.h"
using std::cout;
using std::endl;

int main(){
	Box myBox(40.0,30.0,20.0);
	Carton myCarton;
	Carton candyCarton("Thin cardboard");
	cout << endl
		<< "myBox occupies " << sizeof myBox <<" bytes"<<endl;
	cout << "myCarton occupies "<< sizeof myCarton << " bytes" <<endl;
	cout << "candyCarton occupies "<<sizeof candyCarton <<" bytes" <<endl;
	return 0;
}


Box.h:

#ifndef BOX_H
#define BOX_H
class Box{
public:
	Box(double lv=1.0,double wv=1.0,double hv=1.0);
private:
	double length;
	double width;
	double height;
};
#endif


Carton.h:

#ifndef CARTON_H
#define CARTON_H
#include "Box.h"
class Carton:public Box{
public:
	Carton(const char* pStr="Cardboard");
	~Carton();
private:
	char* pMaterial;
};
#endif


Box.cpp:

#include "Box.h"
Box::Box(double lv,double wv,double hv):length(lv),width(wv),height(hv)
	{}


Carton.cpp:

#include "Carton.h"
#include <cstring>
#include <iostream>
Carton::Carton(const char* pStr){
	pMaterial=new char[strlen(pStr)+1];
 strcpy(pMaterial,pStr);
}
Carton::~Carton(){
	delete[] pMaterial;
}


 

C++继承,布布扣,bubuko.com

C++继承

原文:http://blog.csdn.net/u010142437/article/details/38612397

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!