码迷,mamicode.com
首页 > 编程语言 > 详细

C++继承

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

标签:c++   继承   

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++继承

标签:c++   继承   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!