C++——类访问修饰符

类访问修饰符

数据封装是面向对象编程的一个重要特点,它防止函数直接访问类类型的内部成员。类成员的访问限制是通过在类主体内部对各个区域标记 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 ;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lucas_zgp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值