1. 类和对象
1.1 类的封装
类是对象的抽象化,而类的封装特性包含两个方面,一个是属性和变量合成一个整体,一个是给属性和函数增加访问权限。
- 封装
- 把变量(属性)和函数(操作)合成一个整体,封装在一个类中
- 对变量和函数进行访问控制
- 访问权限
- 在类的内部(作用域范围内),没有访问权限之分,所有成员可以相互访问
- 在类的外部(作用域范围外),访问权限才有意义:public,private,protected
在类的外部,只有public修饰的成员才能被访问,在没有涉及继承与派生时,
//封装两层含义
//1. 属性和行为合成一个整体
//2. 访问控制,现实事物本身有些属性和行为是不对外开放
class Person
{
//人具有的行为(函数)
public:
void Dese(){
cout << "我有钱,年轻,个子又高,就爱嘚瑟!" << endl;}
//人的属性(变量)
int mTall; //多高,可以让外人知道
protected:
int mMoney; // 有多少钱,只能儿子孙子知道
private:
int mAge; //年龄,不想让外人知道
};
int main()
{
Person p;
p.mTall = 220;
//p.mMoney 保护成员外部无法访问
//p.mAge 私有成员外部无法访问
p.Dese();
return EXIT_SUCCESS;
}
class和struct的区别:class默认访问权限为private,struct默认访问权限为public。
class A{
int mAge;
};
struct B{
int mAge;
};
void test(){
A a;
B b;
//a.mAge; //无法访问私有成员
b.mAge; //可正常外部访问
}
1.2通常将成员变量定义为私有属性
1.可赋予客户端访问数据的一致性。
如果成员变量不是public,客户端唯一能够访问对象的方法就是通过成员函数。通过接口对成员属性访问。
2.可细微划分访问控制。
使用成员函数可使得我们对变量的控制处理更加精细。如果我们让所有的成员变量为public,每个人都可以读写它。如果我们设置为private,我们可以实现“不准访问”、“只读访问”、“读写访问”,甚至你可以写出“只写访问”。
#include<iostream>
#include<string>
using namespace std;
class person
{
public:
person(){
cout<<"构造函数调用"<<endl;number = 123456;}
void get_name()
{
cout<<"name:"<<name<<endl;
}
void get_high()
{
cout<<"tall:"<<high<<endl;
}
void get_sex()
{
cout<<"性别:"<<sex<<endl;
}
void put_name(string name){
this->name = name;}
void put_high(float high){
this->high =high;}
void put_sex(char sex){
this->sex = sex;}
void put_age(int age){
this->age = age;}
void get_number(){
cout<<number<<endl;}
private:
string name;//可写可读
float high;//可写可读
char sex;//可写可读
int age;//只能写,不能读
int number;//只能读
};
void main()
<