一、类-封装
- 封装原则:隐藏对象的属性和实现细节,仅对外公开接口,并且控制访问级别。
在面向对象编程中,用类来实现上面的要求。用类实现封装,用封装来实现高内聚,低耦合。高聚合是说一个对象的功能都在内部搞定,紧紧地结合在一起。低耦合是说对象之间的依赖要松散,不要牵一发动全身。只有这样,当系统规模扩大时,才能比较方便。
二、案例一
利用c++中类的封装性来计算立方体的面积和体积。
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
class Cube
{
public:
int m_l,m_w,m_h; //定义成员变量:长宽高
void CubeArea();
void CubeVolume();
};
//面积
void Cube::CubeArea()
{
int area = 0;
area = 2 * m_l * m_h + 2 * m_l * m_w + 2 * m_h * m_w;
std::cout << "立方体面积为:" << area << endl;
}
//体积
void Cube::CubeVolume()
{
int volume = 0;
volume = m_l * m_h * m_w;
cout << "立方体体积为:" << volume << endl;
}
int main() {
Cube c1;
int length, widh, high;
cout << "请输入立方体长:" << endl;
cin >> length;
cout << "请输入立方体宽:" << endl;
cin >> widh;
cout << "请输入立方体高:" << endl;
cin >> high;
c1.m_l = length;
c1.m_w = widh;
c1.m_h = high;
c1.CubeArea();
c1.CubeVolume();
system("pause");
return 0;
}
三、案例二
利用类的封装性来计算点与圆之间的关系,其输出结果为“点在圆上”、“点在圆内”、或“点在圆外”
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
//点类
class Point
{
public:
//设置点类的接口函数
void SetX(int x)
{
m_x = x;
}
int GetX()
{
return m_x;
}
void SetY(int y)
{
m_y = y;
}
int GetY()
{
return m_y;
}
private:
int m_x;
int m_y;
};
//圆类
class Round
{
public:
//设置圆类的接口函数
void SetR(int r)
{
m_r = r;
}
int GetR()
{
return m_r;
}
void SetCenter(Point center)
{
m_center = center;
}
Point Getcenter()
{
return m_center;
}
private:
int m_r; //半径
Point m_center;//圆心坐标
};
//判断圆和点的关系
void isInRound(Round &r, Point p)
{
int distance =
(r.Getcenter().GetX() - p.GetX())*(r.Getcenter().GetX() - p.GetX()) +
(r.Getcenter().GetY()- p.GetY())*(r.Getcenter().GetY() - p.GetY()); //点到圆点的距离平方
int r_distance = r.GetR() * r.GetR();//圆点的平方
if (distance = r_distance)
{
cout << "点在圆上" << endl;
}
else if (distance > r_distance)
{
cout << "点在圆外" << endl;
}
else
{
cout << "点在圆内 " << endl;
}
}
int main() {
Point p1;
p1.SetX(0);
p1.SetY(0);
Round r1;
r1.SetR(2);
r1.SetCenter(p1);
Point p2;
p2.SetX(0);
p2.SetY(2);
isInRound(r1, p2);
system("pause");
return 0;
}