c++ - 在父类中使用 protected 数据,传递给子类

标签 c++ oop class inheritance

当传递到派生类时,如何访问 protected 父类中的数据。

class parent
{ 
    protected:
        int a;
};

class child : public parent
{
    void addOne(parent * &);
};

void child::addOne(parent * & parentClass)
{
    parentClass->a += 1;
}

int main()
{
    parent a;
    child b;

    parent* ap = &a;

    b.addOne(ap);
}

最佳答案

您不能通过指向基类的指针/引用来访问 protected 数据。这是为了防止您破坏其他派生类对该数据可能具有的不变量。

class parent
{
    void f();
    // let's pretend parent has these invariants:
    // after f(), a shall be 0
    // a shall never be < 0.

    protected:
        int a;
};

class child : public parent
{
public:
    void addOne(parent * &);
};


class stronger_child : public parent
{
public:
    stronger_child(int new_a) {
        if(new_a > 2) a = 0;
        else a = new_a;
    }
    // this class holds a stronger invariant on a: it's not greater than 2!
    // possible functions that depend on this invariant not depicted :)
};

void child::addOne(parent * & parentClass)
{
    // parentClass could be another sibling!
    parentClass->a += 1;
}

int main()
{
    stronger_child a(2);
    child b;

    parent* ap = &a;

    b.addOne(ap); // oops! breaks stronger_child's invariants!
}

关于c++ - 在父类中使用 protected 数据,传递给子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8305183/

相关文章:

C++ header 和声明嵌套结构和类语法

c++ - 如何从指向对象的指针 vector 中删除对象?

c++ - 是否重用未定义的 glMapBufferRange 指针?

java - Java 中更好的 OOP 概念

javascript - 基于原型(prototype)的 OO 与基于类的 OO 相比有哪些优势?

c++ - C++-如何在析构函数中删除子类

C++ 链接错误。我究竟做错了什么?

c# - 从 c# 代码传递结构引用以调用在其原型(prototype)中接受结构引用的 c++ DLL 函数

java - 在创建扩展父 fragment 的子 fragment 时调用 newInstance()

python - 类中的函数实例变量