类的访问修饰符

1/类的访问修饰符定义

一个类可以有多个 public、protected 或 private 标记区域。每个标记区域在下一个标记区域开始之前或者在遇到类主体结束右括号之前都是有效的。成员和类的默认访问修饰符是 private。

class Box {
 
   public:
 
  // 公有成员
 
   protected:
 
  // 受保护成员
 
   private:
 
  // 私有成员
 
};

2/ public成员

公有成员在程序中类的外部是可访问的。可以直接数组设置和获取公有变量的值:

#include<iostream>
using  namespace std;
class Box {
public:
	int Lenght{ 1 };
	int width {1 };
    int height{ 1 };
	int volume()
	{
		return Lenght * width * height;
	}
};
 
int main()
{
 
	Box box1{ 1,3, 4 }; //对象成员初始化
	cout << box1.volume()<<endl; //注意成员函数需要带()
	cout<<sizeof(Box) << endl;  //Box 数据类型的大小
	return 0;
}
 

3/ private成员

私有成员在程序中类的外部是不可访问的。可以用构造函数和函数赋值,以及用函数调用,如下:

#include<iostream>
using  namespace std;
class Box 
{
private:
	int Lenght{ 1 };
	int width{ 1 };
	int height{ 1 };
public:
	Box(int x, int y, int z)  //构造函数赋值,也可以用函数赋值
	{
		Lenght = x;
		width = y;
		height = x;
	}
	int getLenght()  //函数调用私用成员
	{
		return Lenght;
	}
};
int main()
{
	Box box1{ 1,3, 4 }; //对象成员初始化
	cout << box1.getLenght() << endl;
	return 0;
}

4/protected成员

protected(受保护)成员变量或函数与私有成员十分相似,但有一点不同,protected(受保护)成员在派生类(即子类)中是可访问的。

#include<iostream>
using  namespace std;
class Box
{
protected:
	int Lenght{ 1 };
};
class SmallBox:Box
{
public:
	void SetLenght(int x)
	{
		Lenght=x;
	}
	int getLenght(void)
	{
		return Lenght;
	}
};

int main()
{
	SmallBox box1;
	box1.SetLenght(10); //对象成员初始化
	cout << box1.getLenght() << endl;
	return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值