gpt4 book ai didi

C++ |重用基类的 protected 成员

转载 作者:行者123 更新时间:2023-11-30 01:25:56 25 4
gpt4 key购买 nike

假设我有一个基类和派生类:

class Base{
private:
int* _privateIntPtrB;
protected:
int* _protectedIntPtrB;
public:
//methods which use
//_privateIntPtrB and _protectedIntPtrB

class Derived: public Base{
private:
int* _privateIntPtrD;
protected:
int* _protectedIntPtrB; //I am redeclaring this var
public:
//methods which use
//_privateIntPtrD and _protectedIntPtrB

我的问题:在 Derived 类的方法中,是否使用了 _protectedIntPtrB 的派生版本? (我认为是的,但想确认)。

如果 Derived 类未重新定义方法,则指向 Derived 类的指针将使用哪个版本的 _protectedIntPtrB

我问的原因 - 我想以不同方式初始化 Derived 类中的 _protectedIntPtrB 并希望使用该版本的 _protectedIntPtrB在派生类的所有实例中。

最佳答案

In the methods of the Derived class, does the Derived version of _protectedIntPtrB get used?

是的,它隐藏了基类成员,因此在 Derived 范围内对 _protectedIntPtrB 的非限定使用指的是 Derived::_protectedIntPtrB . (如果限定为 Base::_protectedIntPtrB,基类变量仍然可用)。

If a method is not redefined by the Derived class, which version of the _protectedIntPtrB will be used by a pointer to Derived class?

基类变量。派生类的数据成员不可从基类获得。

The reason I am asking - I want to initialize _protectedIntPtrB in the Derived class differently and want that version of the _protectedIntPtrB to be used in all the instances of Derived class.

通常,使派生类的行为与其基类不同的最佳方法是覆盖虚函数。如果您能准确地考虑您想要实现的目标,可能会更好:找出您想要修改的行为,并将其封装在虚函数中。

关于C++ |重用基类的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11415259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com