1. 程式人生 > >C++程式設計2018年10月考試設計題程式碼參考

C++程式設計2018年10月考試設計題程式碼參考

設計一個圓類Circle和一個桌子類Table,類Circle包含私有資料成員半徑radius和求圓面積的成員函式getarea(),類Table包含私有資料成員高度height和成員函式getheight(),另設計一個圓桌類Roundtable類Circle和類Table兩個類派生,私有資料成員color和成員函式getcolor(),要求輸出一個圓桌的面積、高度和顏色等資料.
 

VC++6.0解題方法程式碼: 

#include <iostream>
#include <string>
using namespace std;
const double PI = 3.14159;
class Circle
{
private:
    double radius;
public:
    Circle(double r){ radius = r;}
    double getarea(){return radius * radius * PI;}
};
class Table
{
private:
    double height;
public:
    Table(double h){ height = h;}
    double getheight(){ return height; }
};
class Roundtable:public Circle,public Table
{
private:
    char color[8];
public:
    Roundtable(double r,double h,char *c):Circle(r),Table(h)
    { strcpy(color,c);}
    char* getcolor(){return color;}
};
int main()
{
    Roundtable rt(10.0,1.8,"黑色");
    cout << rt.getarea()   << endl;
    cout << rt.getheight() << endl;
    cout << rt.getcolor()  << endl;
    return 0;
}

輸出結果: 

314.159
1.8
黑色

 

VS code 解題方法程式碼:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
const double PI = 3.14159;
class Circle
{
private:
    double radius;
public:
    Circle(double r){ radius = r;}
    double getarea(){return radius * radius * PI;}
};
class Table
{
private:
    double height;
public:
    Table(double h){ height = h;}
    double getheight(){ return height; }
};
class Roundtable:public Circle,public Table
{
private:
    char color[8];
public:
    Roundtable(double r,double h,const char *c):Circle(r),Table(h)
    { strcpy(color,c);}
    char* getcolor(){return color;}
};
int main()
{
    Roundtable rt(10.0,1.8,"黑色");
    cout << rt.getarea()   << endl;
    cout << rt.getheight() << endl;
    cout << rt.getcolor()  << endl;
    return 0;
}

VS 2017解題方法程式碼:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
const double PI = 3.14159;
class Circle
{
private:
	double radius;
public:
	Circle(double r) { radius = r; }
	double getarea() { return radius * radius * PI; }
};
class Table
{
private:
	double height;
public:
	Table(double h) { height = h; }
	double getheight() { return height; }
};
class Roundtable :public Circle, public Table
{
private:
	string color;
public:
	Roundtable(double r, double h, string c) :Circle(r), Table(h)
	{
		color = c;
	}
	string getcolor() { return color; }
	friend ostream &operator << (ostream &,Roundtable);		//使用string類需要運算子過載
};
ostream &operator << (ostream &stream,Roundtable shuchu)
{
	stream << shuchu.color ;
	return stream;
}
int main()
{
	Roundtable rt(10.0, 1.8, "黑色");
	cout << rt.getarea()   << endl;
	cout << rt.getheight() << endl;
	cout << rt.getcolor()  << endl;
	return 0;
}