在C++中,protected关键字用于声明类的成员属性和方法,这些成员可以被类的派生类访问,但是不能被类的对象直接访问。
在使用protected关键字时,可以在类的内部和派生类中访问被声明为protected的成员。示例如下:
class Base {protected:int protectedVar;public:Base() {protectedVar = 10;}void printProtectedVar() {cout << "Protected Variable: " << protectedVar << endl;}};class Derived : public Base {public:void modifyProtectedVar() {protectedVar = 20;cout << "Modified Protected Variable: " << protectedVar << endl;}};int main() {Base obj;obj.printProtectedVar(); // 在类的成员函数中访问protected成员Derived derivedObj;derivedObj.modifyProtectedVar(); // 在派生类的成员函数中访问protected成员return 0;}在这个示例中,Base类中声明了一个protected成员变量protectedVar,并且定义了一个成员函数printProtectedVar来访问该成员变量。Derived类继承自Base类,并且定义了一个成员函数modifyProtectedVar来修改protectedVar的值。在main函数中,分别创建了Base类的对象obj和Derived类的对象derivedObj,并调用了对应的成员函数来访问和修改protected成员。
上一篇:java接收多个文件的方法是什么
下一篇:c++中ofstream的用法是什么
C++









