C++實驗 實驗3 類和物件 1
阿新 • • 發佈:2019-01-31
定義一個圓類,計算圓的面積和周長。
要求:分別用成員函式和友元函式來求圓的面積和周長。
#include<iostream> using namespace std; const double PI = 3.14159; class Circle { public: Circle(double r); double Circumference(); double Area(); friend double fCircle_L(Circle &rr); friend double fCircle_S(Circle &rr); private: double radius; }; Circle::Circle(double r) { radius = r; } //成員函式計算周長 double Circle::Circumference() { cout << "成員函式被呼叫" << endl; return 2 * PI * radius; } //成員函式計算面積 double Circle::Area() { cout << "成員函式被呼叫" << endl; return PI * radius *radius; } //友元函式求周長 double fCircle_L(Circle &r) { cout << "友元函式被呼叫" << endl; double L = 2 * PI * r.radius; return L; } //友元函式求面積 double fCircle_S(Circle &r) { cout << "友元函式被呼叫" << endl; double S = PI * r.radius * r.radius; return S; } int main(void) { double R; cout << "請輸入半徑: "; while(cin >> R) { Circle C(R); cout << C.Circumference() << endl; cout << C.Area() << endl; cout << fCircle_L(C) << endl; cout << fCircle_S(C) << endl; cout << "\n\n請輸入半徑: "; } return 0; }