学堂 学堂 学堂公众号手机端

在C++中,protected关键字用于声明类的成员属性和方法,这些成员可以被类的派生类访问,但是不能被类的对象直接访问

lewis 1年前 (2024-03-12) 阅读数 4 #技术

在C++中,protected关键字用于声明类的成员属性和方法,这些成员可以被类的派生类访问,但是不能被类的对象直接访问。

在使用protected关键字时,可以在类的内部和派生类中访问被声明为protected的成员。示例如下:

classBase{ protected: intprotectedVar; public: Base(){ protectedVar=10; } voidprintProtectedVar(){ cout<<"ProtectedVariable:"<<protectedVar<<endl; } }; classDerived:publicBase{ public: voidmodifyProtectedVar(){ protectedVar=20; cout<<"ModifiedProtectedVariable:"<<protectedVar<<endl; } }; intmain(){ Baseobj; obj.printProtectedVar();//在类的成员函数中访问protected成员 DerivedderivedObj; derivedObj.modifyProtectedVar();//在派生类的成员函数中访问protected成员 return0; }

在这个示例中,Base类中声明了一个protected成员变量protectedVar,并且定义了一个成员函数printProtectedVar来访问该成员变量。Derived类继承自Base类,并且定义了一个成员函数modifyProtectedVar来修改protectedVar的值。在main函数中,分别创建了Base类的对象obj和Derived类的对象derivedObj,并调用了对应的成员函数来访问和修改protected成员。


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门