简简单单学习cpp-类的封装
相关概念
- 封装是把属性和方法封装到类内部,然后给这些数据赋予权限
- 防止乱调用函数和变量 出现错误
- 方便维护代码
# define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "test.h"
class Maker
{
public:
int a;// 成员属性
// 成员方法 函数
void func() {
cout << "func " << endl;
}
};
int main() {
// 普通引用
Maker m;
system("pause");
return EXIT_SUCCESS;
}
简单案例
不能访问私有成员,可以访问公有成员,类外不可以访问保护权限成员,子类可以访问父类的保护成员变量,类内没有权限之分
# define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "test.h"
class Maker
{
public:
void set(string Name, int Id) {
id = Id;
name = Name;
}
void printMaker() {
cout << "id=" << id << " name="
<< name << endl;
}
private:
int id;
string name;
protected:
int a;// 保护属性
};
// 子类类内可以访问父类保护权限的成员
class Son : public Maker {
void func() {
a = 20;
}
};
int main() {
// 封装
Maker m;
m.set("cdahsjdchas", 1);
m.printMaker();
system("pause");
return EXIT_SUCCESS;
}
子类对象访问父类protect
# define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "test.h"
class Maker
{
public:
void set(string Name, int Id) {
id = Id;
name = Name;
}
void printMaker() {
cout << "id=" << id << " name="
<< name << endl;
}
private:
int id;
string name;
protected:
int a;// 保护属性
};
// 子类类内可以访问父类保护权限的成员
class Son : public Maker {
public:
void func() {
a = 20;
}
void getS() {
cout << a << endl;
}
};
int main() {
// 封装
Maker m;
m.set("cdahsjdchas", 1);
// m.printMaker();
Son s;
s.func();
s.getS();
system("pause");
return EXIT_SUCCESS;
}
结构体和类的区别
结构体的默认权限是共有的,累的默认权限是私有的