6.7 設(shè)計(jì)一個圓類circle和一個桌子類table,另設(shè)計(jì)一個圓桌類roundtable,它是從前兩個類派生的,要求輸出一個圓桌的高度、面積和顏色等數(shù)據(jù)。
解:
circle類包含私有數(shù)據(jù)成員radius和求圓面積的成員函數(shù)getarea();table類包含私有數(shù)據(jù)成員height和返回高度的成員函數(shù)getheight()。roundtable類繼承所有上述類的數(shù)據(jù)成員和成員函數(shù),添加了私有數(shù)據(jù)成員color和相應(yīng)的成員函數(shù)。本題程序如下:
#include<iostream.h>
#include<string.h>
class circle
{
double radius;
public:
circle(double r) { radius=r; }
double getarea() { return radius*radius*3.14; }
};
class table
{
double height;
public:
table(double h) { height=h; }
double getheight() { return height; }
};
class roundtable : public table,public circle
{
char *color;
public:
roundtable(double h, double r, char c[]) : circle (r) , table (h)
{
color=new char[strlen(c)+1];
strcpy (color, c);
}
char *getcolor() { return color; }
};
void main()
{
roundtable rt(0.8,1.2,"黑色");
cout << "圓桌屬性數(shù)據(jù):" << endl;
cout << "高度:" <<rt.getheight() << "米" << endl;
cout << "面積:" <<rt.getarea() << "平方米" << endl;
cout << "顏色:" <<rt.getcolor() << endl;
}
本程序的執(zhí)行結(jié)果如下:
圓桌屬性數(shù)據(jù):
高度:0.8米
面積:4.5216平方米
顏色:黑色
北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |