QT-protected

在 Qt 和 C++ 中,protected 是一个访问控制关键字,用于定义类成员(如变量、方法等)的访问权限。protected 提供了一种介于 publicprivate 之间的访问级别,主要用于继承和派生类的情况。

基本概念

  • public:公有成员,可以被任何外部代码访问。
  • protected:受保护成员,只能被当前类及其派生类访问。
  • private:私有成员,只能被当前类内部的成员函数访问。

protected 的具体含义

  1. 当前类访问protected 成员可以被当前类的成员函数和友元函数访问。
  2. 派生类访问protected 成员可以被派生类(子类)的成员函数和友元函数访问,无论继承方式是 publicprotected 还是 private
  3. 外部访问protected 成员不能被类外部的代码直接访问。

使用场景

  • 继承和封装 :当需要允许派生类访问某些成员,但又不想让外部代码直接访问这些成员时,使用 protected
  • 实现细节隐藏:将类的实现细节隐藏起来,只暴露必要的接口,同时允许派生类访问必要的内部实现。

示例代码

以下是一个简单的示例,展示 protected 的使用:

复制代码
#include <iostream>

class Base {
protected:
   int protectedData;

public:
   Base() : protectedData(10) {}

   void showProtectedData() {
       std::cout << "Protected Data: " << protectedData << std::endl;
   }
};

class Derived : public Base {
public:
   void modifyProtectedData() {
       protectedData = 20; // 派生类可以访问 protected 成员
   }

   void showModifiedData() {
       std::cout << "Modified Protected Data: " << protectedData << std::endl;
   }
};

int main() {
   Base base;
   base.showProtectedData();

   Derived derived;
   derived.modifyProtectedData();
   derived.showModifiedData();

   // base.protectedData = 30; // 错误,外部代码不能直接访问 protected 成员

   return 0;
}

输出结果

复制代码
Protected Data: 10
Modified Protected Data: 20

注意事项

  • 继承方式影响 :不同的继承方式(publicprotectedprivate)会影响 protected 成员在派生类中的访问权限。
  • public 继承:protected 成员在派生类中仍然是 protected
  • protected 继承:protected 成员在派生类中变为 protected
  • private 继承:protected 成员在派生类中变为 private
  • 访问控制 :合理使用 protected 可以提高代码的封装性和可维护性,但过度使用可能会导致代码复杂度增加。

通过 protected 访问控制,可以在继承层次中实现灵活的成员访问策略,既保护了类的内部实现,又允许派生类进行必要的访问和扩展。

相关推荐
用户805533698033 小时前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner4 小时前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz5 天前
QML Hello World 入门示例
qt
xcyxiner8 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner9 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner9 天前
DicomViewer (添加模型类)3
qt
xcyxiner10 天前
DicomViewer (目录调整) 2
qt
xcyxiner10 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00612 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术12 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript