author:&Carlton
tags:C++
topic:Class类-Encapsulation封装(附案例)
video:22 类和对象-封装-设计案例2-点和圆关系哔哩哔哩bilibili
date:2023年7月16日
目录
类与对象
万事万物可作为对象(object)看待,例如人、汽车、水杯、钢笔……
物以类聚,人以群分,具有相同性质的对象可以分为一类(class)
对象具有属性(成员属性 attribute)和行为(函数成员 function member),以人为例:
人具有各自的属性:年龄,身高,情人……
人也具有各自的行为:回答年龄与身高,结交伴侣等等
*正如例子所示,同类对象具有“相同”的属性和行为(都有这个空可填,只是填的内容不同,填的东西是: 数据成员 data member)
因此在C++,通过类,我们能很方便基于对象进行处理,以对象为主体来完成我们编程的目的,用更笼统、通俗的概念解决问题。我们声明一种“类”,并由此定义这类对象(实例化,instantiation)
封装
封装(encapsulation)使得类中的成员拥有访问权限,可以灵活使用public、private、protected三种访问权限类型提供接口、密闭的属性等等,也是不同于结构体struct的重要因素(struct默认为public,struct声明外亦可访问)
由于类封装的特点,我们能灵活分类私有的属性和公有的属性,简单的实现有:
//建立立方体类
class Cube
{
//私有,属性 长long 宽wide 高high
private:
int c_l, c_w, c_h;
//公开,行为
public:
//set 设置属性
void set_l(int l)
{
c_l = l;
}
void set_w(int w)
{
c_w = w;
}
void set_h(int h)
{
c_h = h;
}
//get 得到立方体表面积 S 和体积 V
int get_S()
{
return 2*(c_h*c_l+c_h*c_w+c_l*c_w);
}
int get_V()
{
return c_l*c_w*c_h;
}
//成员函数,传递同类的另一个对象即可
bool IsSame(Cube c1)
{
if (c1.c_l == c_l && c1.c_w == c_w && c1.c_h == c_h)
{
return true;
}
return false;
}
};
案例——点与圆的关系(多文件编程)
案例描述
定义一个圆(圆心和半径)和点(坐标),判断点在圆上/外/内。
对象提取
圆和点
文件情况
头文件:分别放类-圆 Circle 和类-点 Point的声明
源文件:分别放两个类各自的成员函数的定义、main函数(注意用作用域操作符 : : 指明对应的作用域(命名空间))
源代码实现
1.Circle.h
#pragma once
#include <iostream>
//包含Point类头文件
#include "Point.h"
using namespace std;
class Circle
{
private:
int r;
//在一个类中使用另一个类
Point center;
public:
void setr(int r1);
void setcenter(Point p);
void isInCircle(Point p);
};
2.Point.h
//解决出现因为多次调用头文件出现的多重定义问题
#pragma once
#include <iostream>
using namespace std;
//Point 类声明,包含其属性与成员函数声明
class Point
{
public:
int x, y;
void setx(int x1);
void sety(int y1);
};
3.Circle.cpp
#include "Circle.h"
void Circle::setr(int r1)
{
r = r1;
}
void Circle::setcenter(Point p)
{
center = p;
}
void Circle::isInCircle(Point p)
{
double distance = sqrt(pow(p.x - center.x, 2) + pow(p.y - center.y, 2));
if (distance > r)
{
cout << "点在圆外" << endl;
}
else if (distance == r)
{
cout << "点在圆上" << endl;
}
else
{
cout << "点在圆内" << endl;
}
}
//圆和点的关系
4.Point.cpp
#include "Point.h"
//在Point作用域下的setx函数
void Point::setx(int x1)
{
x = x1;
}
//在Point作用域下的sety函数
void Point::sety(int y1)
{
y = y1;
}
5.类-封装-圆和点.cpp
#include "Point.h"
//在Point作用域下的setx函数
void Point::setx(int x1)
{
x = x1;
}
//在Point作用域下的sety函数
void Point::sety(int y1)
{
y = y1;
}
运行结果
反思与总结
学习视频后及时记录疑难点、自己独立敲代码复现,在此过程中发现自己的知识盲区并对点解决。
重点:
①多文件编程-类的成员函数与作用域
②类的访问权限
欢迎指正与分享,谢谢!