【C++基础】类和对象——封装
C++面向对象的三大特征:封装
、继承
、多态
对象包含属性和行为。
封装
封装的意义
- 将属性和行为作为一个整体,表现为一个具体的事物
- 将属性和行为加以权限控制
访问权限
- public 公共权限:类内可以访问,类外可以访问
- protexted 保护权限:类内可以访问,类外不可以访问,继承可以访问
- private 私有权限:类内可以访问,类外不可以访问,继承不可以访问
语法:class 类名 { 访问权限: 属性; 行为; };
示例:
#include<iostream>
using namespace std;
class human
{
public: //公有属性,外界可以访问
string name;
void speak()
{
cout << name << "说:" << "“1 + 1 = 2 !!!”" << endl;
};
private: //私有属性,外界不可以访问
int age;
};
void main()
{
human h1;
h1.name = "张三";
h1.speak();
}
输出:
访问下私有属性age
私有属性不可访问,私有函数同理。
二、struct和class的区别
唯一区别就是默认访问权限不同
区别:
- struct 默认权限为公共
- class 默认权限为私有
示例:
#include<iostream>
using namespace std;
class Cls
{
int num_cls; //默认为私有权限
};
struct Stc
{
int num_stc; //默认为公共权限
};
void main()
{
Cls c;
//c.num_cls; 不能访问
Stc s;
s.num_stc;
}
报错:
三、成员属性设为私有
- 控制读写权限
- 检测写入数据
示例:
#include<iostream>
using namespace std;
class Student
{
public: //函数外可以访问
void setName(string na)
{
name = na;
};
string getName()
{
return name;
};
private: //函数外不可以访问
string name;
};
void main()
{
Student s;
s.setName("张三");
cout << s.getName() << endl;
}
输出: