目录
1.封装是什么
c++认为万事万物都可以称为对象,而具有相同特性的对象可以抽象为一类
class代表的是一个类,而一个类后面紧跟着的就是它的名称
封装使用的就是class关键字
内部分为访问权限,属性,行为
属性和行为统一称为成员
属性又称成员属性或则成员变量
行为又称为成员函数或则成员方法
再到主函数中实例化,即通过类,创立一个对象的过程
2.封装的示例
举例:计算圆的周长
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
class circle
{
public:
int r;
double zhouchang()
{
return 2 * 3.14 * r;
}
};
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
circle yuan;
cin >> yuan.r;
cout << yuan.zhouchang();
return 0;
}
3.封装的意义
4.class与struct的区别
唯一的区别在于默认的访问权限不同
struct默认权限为公共
class默认权限为私有 ,意思就是说如果成员上面什么权限都不写那它就是私有权限
5.示例:点与圆的关系
在类中可以让另一个类作为本类的成员
点可能在圆外,圆上,圆内
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
class point
{
public:
void setx(int x){
mx = x;
}
int getx() {return mx;}
void sety(int y){
my = y;
}
int gety() {return my;}
private:
int mx;
int my;
};
class circle
{
public:
void setr(int r) {mr = r;}
int getr() {return mr;}
void setcenter(point p) {mcenter = p;}
point getcenter() {return mcenter;}
private:
int mr;
point mcenter;
};
void isincircle(circle &c,point &p){
int distance =
(c.getcenter().getx() - p.getx())*(c.getcenter().getx() - p.getx())+
(c.getcenter().gety() - p.gety())*(c.getcenter().gety() - p.gety());
int rdistance = c.getr() * c.getr();
if(distance > rdistance) cout << "点在圆外" << '\n';
else if(distance == rdistance) cout << "点在圆上" << '\n';
else cout << "点在圆内" << '\n';
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
//建立初始圆
circle c;
c.setr(5);
point center;
center.setx(0);
center.sety(0);
c.setcenter(center);
//三次判断
for(int i = 0; i < 3; i++){
point judgepoint;
int x,y;
cin >> x >> y;
judgepoint.setx(x);
judgepoint.sety(y);
isincircle(c,judgepoint);
}
return 0;
}