随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
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;
}