面向对象程序设计的4个主要特征:抽象,封装,继承和多态。
类是一些具有相同属性和行为的对象的抽象。
对象是某个特定类所描述的实例。
类是对象的抽象,而对象是类的实例。
类中两种特殊的函数:
(ctor)构造函数:在创建对象时被自动调用
(dtor)析构函数:在对象被销毁时被自动调用
类的定义格式:
class 类名 //类名是标志符,首字符采用大写字母
{
private:
数据成员或成员函数 //数据成员代表对象的属性,成员函数代表实现对象的行为
protected:
数据成员或成员函数
public:
数据成员或成员函数
}
注意:
- 不能在类声明中给数据成员赋初值;
- 类是抽象的名词,而不是具体的对象。因此,在定义类时不能对数据成员进行赋值。
在C++类中,可以定义3种不同访问控制权限的成员。这三种不同的访问权限符分别为public(公有类型)、private(私有类型)和protected(保护类型)。
- public:(公有类型)
public声明成员为公有成员。具有这个访问控制级别的成员是完全公开的,即该成员不但可以被它所在类的成员函数及该类的友元函数访问,而且也可以被和该类对象处在同一作用域内的任何函数访问。
#include"iostream"
using namespace std;
class human
{
public: //声明类的公有成员
int stature;
int weight;
void getstature()
{
cout<<"your stature is:"<<stature<<endl;
}
void getweight()
{
cout<<"your weight is:"<<weight<<endl;
}
} ;
int main()
{
human tom; //定义类的对象
tom.stature=185; //通过对象访问类的公有数据成员
tom.weight=90; //通过对象访问类的公有数据成员
tom.getstature(); //通过对象访问类的公有成员函数
tom.getweight(); //通过对象访问类的公有成员函数
return 0;
}
运行结果界面:
2. private:(私有类型)
private声明成员为私有成员。具有这个访问控制级别的成员对类外是完全保密的,即只能被它所在类中的成员函数和该类的友元函数访问。
#include"iostream"
using namespace std;
class human
{
private: //声明类的私有成员
int stature;
int weight;
public: //声明类的公有成员
void setstature(int s)
{
stature=s; //类的成员函数访问类的私有数据成员
}
void getstature()
{
cout<<"your stature is:"<<stature<<endl; // 类的成员函数访问类的私有数据成员
}
void setweight(int w)
{
weight=w; // 类的成员函数访问类的私有数据成员
}
void getweight()
{
cout<<"your weight is:"<<weight<<endl; //类的成员函数访问类的私有数据成员
}
} ;
int main()
{
human tom; //定义类的对象
//tom.stature=185; //错误,不能通过对象访问类的私有数据成员
//tom.weight=90; //错误,不能通过对象访问类的私有数据成员
tom.setstature(185); //通过对象访问类的公有成员函数给stature赋值
tom.setweight(90); //通过对象访问类的公有成员函数 给weight赋值
tom.getstature() ; //通过对象访问类的公有数据成员
tom.getweight() ; //通过对象访问类的公有数据成员
return 0;
}
运行结果界面:
3. protected:(保护类型)
protected声明成员为保护成员。具有这个访问控制级别的成员,外界是无法直接访问的。它能被它所在类及该类派生的子类的成员函数及友元函数访问。
#include"iostream"
using namespace std;
class human
{
protected: //声明类的保护数据成员
int stature;
int weight;
public: //声明类的公有成员
void setstature(int s)
{
stature=s; //类的成员函数访问类的保护数据成员
}
void getstature()
{
cout<<"your stature is:"<<stature<<endl; // 类的成员函数访问类的保护数据成员
}
void setweight(int w)
{
weight=w; // 类的成员函数访问类的保护数据成员
}
void getweight()
{
cout<<"your weight is:"<<weight<<endl; //类的成员函数访问类的保护数据成员
}
} ;
int main()
{
human tom; //定义类的对象
//tom.stature=185; //错误,不能通过对象访问类的保护数据成员
//tom.weight=90; //错误,不能通过对象访问类的保护数据成员
tom.setstature(185); //通过对象访问类的公有成员函数给stature赋值
tom.setweight(90); //通过对象访问类的公有成员函数 给weight赋值
tom.getstature() ; //通过对象访问类的公有数据成员
tom.getweight() ; //通过对象访问类的公有数据成员
return 0;
}
运行结果界面:
总结:protected成员和private成员一样只能在类内访问,类外不能通过对象访问。但二者唯一的区别是protected成员能被派生类的成员访问。