类访问修饰符
数据封装是面向对象编程的一个重要特点,它防止函数直接访问类类型的内部成员。类成员的访问限制是通过在类主体内部对各个区域标记 public、private、protected 来指定的。关键字 public、private、protected 称为访问修饰符。
共有成员(public)
公有成员在程序中类的外部是可访问的。可以不使用任何成员函数来设置和获取公有变量的值
#include <iostream>
using namespace std ;
class Box
{
public :
int Lenth ;
int Width ;
int Height ;
void SetLenth(int len);
int GetLenth(void);
};
int Box::GetLenth(void)
{
return Lenth ;
}
void Box::SetLenth(int len)
{
Lenth = len ;
}
void main()
{
// 使用成员函数
Box box ;
box.SetLenth(2);
cout << "Lenth is " <<box.GetLenth()<< endl;
// 不使用成员函数
box.Lenth = 4 ;
cout << "Lenth is " << box.Lenth << endl ;
}
/* 运行结果
Lenth is 2
Lenth is 4
*/
私有成员(private)
私有成员变量或函数在类的外部是不可访问的,甚至是不可查看的。只有类和友元函数可以访问私有成员。
#include <iostream>
using namespace std ;
class Box
{
public :
void SetLenth(int len);
int GetLenth(void);
private:
int Lenth ;
int Width ;
int Height ;
};
int Box::GetLenth(void)
{
return Lenth ;
}
void Box::SetLenth(int len)
{
Lenth = len ;
}
void main()
{
// 使用成员函数
Box box ;
box.SetLenth(2);
cout << "Lenth is " <<box.GetLenth()<< endl;
// 不使用成员函数,编译出错。 因为Lenth 是私有的。不能在类的外部直接访问
// box.Lenth = 4 ;
// cout << "Lenth is " << box.Lenth << endl ;
}
保护成员(protected)
保护成员变量或函数与私有成员十分相似,但有一点不同,保护成员在派生类(即子类)中是可访问的。
#include <iostream>
using namespace std ;
class Box
{
public :
void SetLenth(int len);
int GetLenth(void);
private:
int Width ;
int Height ;
protected:
int Lenth ;
};
class SmallBox:Box // SmallBox 是派生类
{
public :
void SetSmallLenth(int len);
int GetSmallLenth(void);
};
// 子类的成员函数 可以 直接访问父类的受保护变量
int SmallBox::GetSmallLenth(void)
{
return Lenth ;
}
void SmallBox::SetSmallLenth(int len)
{
Lenth = len ;
}
void main()
{
SmallBox box ;
box.SetSmallLenth(5);
cout << "Lenth is " << box.GetSmallLenth() << endl ;
}