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("李二");//只写

}

相关推荐
Lhan.zzZ33 分钟前
笔记_2026.4.28_004
c++·ide·笔记·qt
MATLAB代码顾问1 小时前
5大智能算法优化标准测试函数对比(Python实现)
开发语言·python
wuminyu2 小时前
专家视角看Java字节码加载与存储指令机制
java·linux·c语言·jvm·c++
万粉变现经纪人2 小时前
如何解决 pip install llama-cpp-python 报错 未安装 CMake/Ninja 或 CPU 不支持 AVX 问题
开发语言·python·开源·aigc·pip·ai写作·llama
清风明月一壶酒3 小时前
OpenClaw自动处理Word文档全流程
开发语言·c#·word
其实防守也摸鱼3 小时前
CTF密码学综合教学指南--第五章
开发语言·网络·笔记·python·安全·网络安全·密码学
木喃的井盖3 小时前
无锁队列细节
c++·工程
王老师青少年编程3 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:输出亲朋字符串
c++·字符串·csp·高频考点·信奥赛·专项训练·输出亲朋字符串
MediaTea3 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z4 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode