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;
}