C++学习笔记
第1章 封装
1.1 封装的意义
封装 是C++的面向对象三大特性之一。
封装的意义:
1.将属性和行为作为一个整体,表现生活中的事物。
2.将属性和行为加以权限控制。
在设计的时候,将属性和行为写在一起,表现事物。
语法:
class 类名{ 访问权限:属性/行为};
#include<iostream>
using namespace std;
const double PI=3.14;
class Circle
{
//访问权限
public:
//属性
int m_r;
double circulateZC()
{
return 2*PI*m_r;
}
};
int main()
{
//通过类,创建具体的对象(实例化)
Circle c1;
//给对象参数赋值
c1.m_r = 10;
cout<<"圆的周长为:"<<c1.circulateZC()<<endl;
system("pause");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
class Student
{
public: //公共权限
//属性 成员属性 成员变量
//行为 成员函数 成员方法
//属性
string m_Name;
int m_Id;
//行为
void showStudent()
{
cout<<"姓名:"<<m_Name<<"学号:"<<m_Id<<endl;
}
void setName(string name)
{
m_Name = name;
}
void setId(string id)
{
m_Id = id;
}
};
int main()
{
//通过类,创建具体的对象(实例化)
Student s1;
Student s2;
//给对象参数赋值
s1.m_Name ="张三";
// s1.m_Id =1;
s1.setId(1);
s1.showStudent();
s2.m_Name ="李四";
s2.m_Id =2;
s2.setId(2);
s2.showStudent();
system("pause");
return 0;
}