类和对象——封装——属性和行为作为整体
c++面向对象的三大特性为:封装,继承,多态。c++认为万事万物皆为对象,并且有属性和行为。
封装的意义:
- 将属性和行为作为一个整体,表现生活中的事物
- 将属性和行为加以权限控制
语法: class 类名{ 访问权限:属性 / 行为 };
示例1:设计一个圆类,求圆的周长与面积
#include<iostream>
using namespace std;
class circle
{
public:
int radius;//成员对象(属性)
double getarea()//成员函数(行为)
{
return radius*radius*3.14;
}
double getperimeter()//成员函数(行为)
{
return 2*radius*3.14;
}
};
void test01()
{
circle p1;//创建对象p1
p1.radius=3;//赋值半径为3
p1.getarea();
p1.getperimeter();
cout<<"面积:"<<p1.getarea()<<endl;
cout<<"周长:"<<p1.getperimeter()<<endl;
}
int main()
{
test01();
return 0;
}