C++类中私有属性的获取
计算椭圆面积的案例
#include <iostream>
#include <math.h>
#include <iomanip> //输入输出cin,cout
using namespace std;
class Ellipse
{
private:
int x1,y1,x2,y2;
public:
//构造函数
Ellipse(int xx1,int yy1,int xx2,int yy2);
//计算面积的函数
double Area();//计算椭圆面积
int GetX1(){return x1;} //私有属性返回
int GetY1(){return y1;}
int GetX2(){return x2;}
int GetY2(){return y2;}
};
Ellipse::Ellipse(int xx1,int yy1,int xx2,int yy2)
{
x1 = xx1; y1 = yy1; x2 = xx2; y2 = yy2;
}
double Ellipse::Area()
{
return (double)( 3.1415 * fabs(x2-x1) * fabs(y2-y1) / 4 ); //椭圆面积公式:s=π*a*b(其中a、b是半长轴)
}
int main()
{
int x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2; //输入
Ellipse e(x1,y1,x2,y2);
cout << e.GetX1() << " " << e.GetY1() << " " << e.GetX2() << " " << e.GetY2() << endl; //取得私有属性并输出
cout << fixed << setprecision(4) << e.Area() << endl; fixed与setprecision(4)配合使用,可控制只输出4位小数
return 0;
}
喜欢的朋友可以关注我的个人公众号,后台回复java资料可免费领取资源。