C++中的私有和保护成员


C++中的类具有公共、私有和保护部分,这些部分包含相应的类成员。

私有数据成员无法从类外部访问。它们只能被类或友元函数访问。默认情况下,所有类成员都是私有的。

类中的保护成员类似于私有成员,但派生类或子类可以访问它们,而私有成员则不能。

演示类中私有和保护成员的程序如下所示:

示例

在线演示

#include <iostream>
using namespace std;
class Base {
   public :
   int a = 8;
   protected :
   int b = 10;
   private :
   int c = 20;
};
class Derived : public Base {
   public :
   void func() {
      cout << "The value of a : " << a;
      cout << "\nThe value of b : " << b;
   }
};
int main() {
   Derived obj;
   obj.func();
   return 0;
}

输出

以上程序的输出如下所示。

The value of a : 8
The value of b : 10

现在,让我们了解一下上面的程序。

在Base类中,数据成员为a、b和c,它们分别是公共的、受保护的和私有的。代码片段如下所示。

class Base {
   public :
   int a = 8;
   protected :
   int b = 10;
   private :
   int c = 20;
};

Derived类继承Base类。func()函数打印a和b的值。它无法打印c的值,因为c对Base类是私有的,无法在Derived类中访问。代码片段如下所示。

class Derived : public Base {
   public :
   void func() {
      cout << "The value of a : " << a;
      cout << "\nThe value of b : " << b;
   }
};

在main()函数中,创建了Derived类的对象obj。然后调用func()函数。代码片段如下所示。

int main() {
   Derived obj;
   obj.func();
   return 0;
}

更新于:2020年6月26日

8K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.