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