13-1类与对象

(一)封装-属性和行为作为

定义语法:class 类名{访问权限:属性/行为};

类中的属性和行为统称为成员

属性称成员属性、成员变量

行为称为成员函数、成员方法

#include <iostream>

using namespace std;

const double pai=3.14;

class circle//class代表设计一个类,类后面紧跟着的为类的名称

{

public://访问权限------公共权限

int r;//属性

double calculateZC()//行为------获取圆的周长

{

return 2*pai*r;

}

};

int main()

{

circle c1;//通过圆类创建一个具体的圆 (对象)

c1.r=10;

cout<<"圆的周长为:"<<c1.calculateZC()<<endl;

return 0;

}

案例------设计学生类

#include <iostream>

#include <cstring>

using namespace std;

class student

{

public:

string name;

int ID;

void showstudent()

{

cout<<"姓名:"<<name<<endl;

cout<<"ID:"<<ID<<endl;

}

};

int main()

{

class student s;

s.name="张一";

s.ID=10425;

s.showstudent();

return 0;

}

#include <iostream>

#include <cstring>

using namespace std;

class student

{

public:

string name;

int ID;

void showstudent()

{

cout<<"姓名:"<<name<<endl;

cout<<"ID:"<<ID<<endl;

}

void setname(string name1)

{

name=name1;

}

void setID(int ID1)

{

ID=ID1;

}

};

int main()

{

class student s;

s.setname("张一");

s.setID(10425);

s.showstudent();

return 0;

}


(二)封装-访问权限

访问权限:1.公共权限 public 成员类内可以访问,类外可以访问

2.保护权限 protected 成员类内可以访问,类外不可以访问

3.私有权限 private 成员类内可以访问,类外不可以访问

#include <iostream>

#include <cstring>

using namespace std;

class person

{

public:

string name;

protected:

string car;

private:

int password;

public:

void f()

{

name="张一";

car="自行车";

password=123456;

}

};

int main()

{

person p;

p.name="李二";

}

类内可以访问

类外不可以访问


(三)封装-C++中的class与struct

C++的class与struct的区别默认的访问权限不同,class默认的权限是private私有,struct默认的权限是公共public

#include <iostream>

using namespace std;

class c

{

int a;//默认权限私有

};

struct s

{

int b;//默认权限公共

};

int main()

{

/*c c1;

c1.a;*/

s s1;

s1.b=100;

cout<<s1.b;

return 0;

}


(四)封装-成员属性私有化

优点:1.将所有成员属性设为私有,可以控制自己的读写权限

2.对于写权限,可以检测数据的有效性

#include <iostream>

using namespace std;

#include <cstring>

class person

{

public:

void setname(string name1)

{

name=name1;

}

string getname()

{

return name;

}

int getage()

{

age=18;

return age;

}

void setfamily(string family1)

{

family=family1;

}

private:

string name;//可读可写

int age;//只读

string family;//只写

};

int main()

{

person p;

p.setname("张一");

cout<<"姓名:"<<p.getname()<<endl;

cout<<"年龄:"<<p.getage()<<endl;

p.setfamily("李二");//只写

}

相关推荐
复杂网络33 分钟前
Stable Diffusion 视觉大模型微调技术深度调研
算法
复杂网络35 分钟前
基于 Stable Diffusion 架构的视觉大模型代表性工作与原理深度解析
算法
MrZhao40043 分钟前
Agent Loop 如何用 Hook 扩展:权限、日志与工具拦截
算法
MrZhao4001 小时前
Agent 为什么需要 Skills:别把所有知识都塞进 system prompt
算法
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2122 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack203 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树3 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2123 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2123 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法