硬核对象到了(滑稽)
类和对象
对象三大特性:封装,继承,多态
万事万物皆为对象,对象上有其属性和行为
封装
简单运用
#include<iostream>
using namespace std;
const double pi = 3.1415;
class circle
{
//访问权限
//公共
public:
//属性
int r;
//行为
double zhouchang()
{
return 2 * pi * r;
}
};
int main()
{
//创造对象
circle c1;
//属性
c1.r = 10;
cout << "周长" << c1.zhouchang() << endl;
system("pause");
return 0;
}
作业
**
#include<iostream>
#include<string>
using namespace std;
//设计学生类,属性有姓名和学号
//给姓名和学号赋值,可以显示学生的姓名和学号
class stu
{
public:
string name;
int id;
void show()
{
cout << "学生姓名: " << name << endl
<< "学生ID: " << id << endl;
}
};
int main()
{
stu stu1;
stu1.name = "xiaoming";
stu1.id = 123;
stu1.show();
system("pause");
return 0;
}
结果:
学生姓名: xiaoming
学生ID: 123
请按任意键继续. . .
访问权限
//访问权限:三种
默认权限是私有权限
//公共权限:public
//保护权限:protected
//私有权限:private
struct和class的区别
访问权限不同;
struct默认权限:公共权限
class默认权限:私有权限