uacs2024

导航

C++ 类访问修饰符

私有(private)成员

成员和类的默认访问修饰符是 private,如果没有使用任何访问修饰符,类的成员将被假定为私有成员。私有成员变量或函数在类的外部是不可访问的,甚至是不可查看的。只有类和友元函数可以访问私有成员。

实际操作中,我们一般会在私有区域定义数据,在公有区域定义相关的函数,以便在类的外部也可以调用这些函数。

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 class Box
 6 {
 7    public:
 8       double length;
 9       void setWidth( double wid );
10       double getWidth( void );
11  
12    private:
13       double width;
14 };
15  
16 // 成员函数定义
17 double Box::getWidth(void)
18 {
19     return width ;
20 }
21  
22 void Box::setWidth( double wid )
23 {
24     width = wid;
25 }
26  
27 int main( )
28 {
29    Box box;
30  
31    // 不使用成员函数设置长度
32    box.length = 10.0; // OK: 因为 length 是公有的
33    cout << "Length of box : " << box.length <<endl;
34  
35    // 不使用成员函数设置宽度
36    // box.width = 10.0; // Error: 因为 width 是私有的
37    box.setWidth(10.0);  // 使用成员函数设置宽度
38    cout << "Width of box : " << box.getWidth() <<endl;
39  
40    return 0;
41 }

protected(受保护)成员

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

 

private 成员只能被本类成员(类内)和友元访问,不能被派生类访问;

 

posted on 2024-03-02 10:55  ᶜʸᵃⁿ  阅读(6)  评论(0编辑  收藏  举报