#include
using namespace std;
class rectangle
{
protected:
double length,width,l,w;
public:
void setlength();
void getlength();
void setwidth();
void getwidth();
double area();
double perimeter();
double diagmonal();
};
void rectangle::setlength()
{
cout<<"please enter the length of rectangle(box):";
cin>>l;
}
void rectangle::getlength()
{
length=l;
}
void rectangle::setwidth()
{
cout<<"please enter the width of rectangle(box):";
cin>>w;
}
void rectangle::getwidth()
{
width=w;
}
double rectangle::area()
{
return(length*width);
}
double rectangle::perimeter()
{
return(2*(length+width));
}
double rectangle::diagmonal()
{
double x=length*length+width*width;
return(sqrt(x));
}
class box:protected rectangle
{
protected:
double height,h;
public:
void setheight();
void getheight();
double area();
double perimeter();
double diagmonal();
double volume();
};
void box::setheight()
{
cout<<"please enter the height for box:";
cin>>h;
}
void box::getheight()
{
height=h;
}
double box::area()
{
return(2*(length*width+length*height+width*height));
}
double box::perimeter()
{
return(4*(length+width+height));
}
double box::diagmonal()
{
return(sqrt(length*length+width*width+height*height));
}
double box::volume()
{
return((length*width)*height);
}
int main()
{
rectangle r;
box b;
r.setlength();
r.getlength();
r.setwidth();
r.getwidth();
b.setheight();
b.getheight();
cout<<"the box's volume is:"<<b.volume()<<endl;
}
如果你非要用protected繼承,那只能這樣:
#include <iostream>
#include <math.h>
using namespace std;
class rectangle
{
protected:
double length,width,l,w;
public:
void setlength();
void getlength();
void setwidth();
void getwidth();
double area();
double perimeter();
double diagmonal();
};
void rectangle::setlength()
{
cout<<"please enter the length of rectangle(box):";
cin>>l;
}
void rectangle::getlength()
{
length=l;
}
void rectangle::setwidth()
{
cout<<"please enter the width of rectangle(box):";
cin>>w;
}
void rectangle::getwidth()
{
width=w;
}
double rectangle::area()
{
return(length*width);
}
double rectangle::perimeter()
{
return(2*(length+width));
}
double rectangle::diagmonal()
{
double x=length*length+width*width;
return(sqrt(x));
}
class box:protected rectangle
{
protected:
double height,h;
public:
void setheight();
void getheight();
double area();
double perimeter();
double diagmonal();
double volume();
};
void box::setheight()
{
cout<<"please enter the height for box:";
cin>>h;
}
void box::getheight()
{
height=h;
cout << height << endl;
}
double box::area()
{
return(2*(length*width+length*height+width*height));
}
double box::perimeter()
{
return(4*(length+width+height));
}
double box::diagmonal()
{
return(sqrt(length*length+width*width+height*height));
}
double box::volume()
{
setlength();
getlength();
setwidth();
getwidth();
return((length*width)*height);
}
int main()
{
box * p = new box;
p->setheight();
p->getheight();
cout<<"the box's volume is:"<<p->volume()<<endl;
delete p;
p = NULL;
}