c++ - 从派生类访问基类公共(public)成员

标签 c++ inheritance

是否可以从程序中其他一些位置的派生类实例访问基类公共(public)成员。

class base {
public:
    int x;

    base(int xx){
    x = xx;
    }
};

class derived : base {
public:
    derived(int xx) : base(xx){
    }
};

class main {
public:
    derived * myDerived;      

    void m1(){
        myDerived = new derived(5);
        m2(myDerived);  
    }

    void m2(derived * myDerived){
        printf("%i", myDerived->x);
    }    
};

在上面的代码之后,我得到了以下错误。

`error: 'int base::x' is inaccessible`

最佳答案

问题是你不小心在这里使用了私有(private)继承

class derived : base {

这使得所有基类成员在派生类中都是私有(private)的。

将此更改为

class derived : public base {

它会按预期工作。

关于c++ - 从派生类访问基类公共(public)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13159659/

相关文章:

Ruby 继承循环

c++ - 求模拟粒子轨迹的3D点和 vector 几何C++库

c++ - 不完整类型的无效使用/前向声明

c++ - Parent 类型的继承容器不能容纳 child ?

c++ - 可选功能的设计模式?

c++ - 子类会影响虚拟方法的可见性吗?

c++ - 不能使用继承、纯虚方法分配抽象类型的对象

c++ - 关于C++中的pow函数

c++ - 动态 ArrayList 的线性和二进制搜索

C++程序没有进入for循环