#include<iostream>
using namespace std;
class Base
{
protected:
double h;
public:
virtual void disp(){} //虚函数disp
Base(){}
Base(double h1)
{h=h1;}
};
class Cuboid:public Base //定义长方体派生类
{
private:
double w,l;
public:
Cuboid(double a=0,double b=0,double h=0):Base(h)
{l=a;w=b;}
void disp()
{
cout<<"长方体:"<<endl;
cout<<"长:"<<l<<"\t宽:"<<w<<"\t高:"<<h<<endl;
cout<<"长方体的体积="<<w*l*h<<endl;
}
};
class Cylinder:public Base //定义圆柱体派生类
{
private:
double r;
public:
Cylinder(double c=0,double h1=0):Base(h1)
{r=c;}
void disp()
{
cout<<"圆柱体:"<<endl;
cout<<"半径:"<<r<<"\t高:"<<h<<endl;
cout<<"圆柱体的体积="<<r*r*h*3.14<<endl;
}
};
int main()
{
Base *pc;
Cuboid Cu(6,8,20);
Cylinder Cy(3,7);
pc=&Cu;
pc->disp();
pc=&Cy;
pc->disp();
return 0;
}
编译过程中出现error C2248: 'h' : cannot access private member declared in class 'Base的错误提醒,原因是把基类中的保护成员写成了私有成员,导致派生类无法访问成员中的数据。这是由于自己对类的继承方式的不熟练,在翻阅书本后,现已改正编译错误,成功运行。