c++中面向对象三大特性:封装,继承,多态,以下介绍封装:类和对象
类是一类事物的统称,是定义实例的模板, c++中万物皆可为对象,对象上有其属性和行为。
以下是定义一个圆类,包含圆中需要的Π这个成员变量和成员方法,并在main中实例化圆这个对象,注意的是类是一个模板。
#include "iostream"
#include "string"
using namespace std;
//设计圆类
class Circle
{
const double PI = 3.14;
public: int r;
double clCr(){
return 2*PI*r;
}
};
//设计学生类
class Student
{
public:
int id;
string name;
void showStudent()
{
cout<<"id="<<id<<"\t"<<"name = "<<name<<endl;
}
};
int main(void)
{
//实例化对象:通过一个类创建一个对象
Circle c1;
//给实例化对象的属性赋值;
c1.r = 10;
//调用实例化对象的行为(方法)
double rs = c1.clCr();
cout<<rs<<endl;
//实例化对象:通过一个类创建一个对象
Student s1;
s1.id = 1000;
s1.name = "小明";
s1.showStudent();
exit(0);
}