c++

c++中的protected怎么使用

小亿
136
2024-02-22 16:52:31
栏目: 编程语言

在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成员。

0
看了该问题的人还看了