相关疑难解决方法(0)

访问另一个子类中的基类的受保护成员

为什么编译:

class FooBase
{
protected:
    void fooBase(void);
};

class Foo : public FooBase
{
public:
    void foo(Foo& fooBar)
    {
        fooBar.fooBase();
    }
};
Run Code Online (Sandbox Code Playgroud)

但这不是吗?

class FooBase
{
protected:
    void fooBase(void);
};

class Foo : public FooBase
{
public:
    void foo(FooBase& fooBar)
    {
        fooBar.fooBase();
    }
};
Run Code Online (Sandbox Code Playgroud)

一方面,C++为该类的所有实例授予对私有/受保护成员的访问权限,但另一方面,它不授予对所有子类实例的基类的受保护成员的访问权限.这看起来与我不一致.

我已经使用VC++和ideone.com测试了编译,并且编译了第一个但不是第二个代码片段.

c++ inheritance encapsulation protected

35
推荐指数
3
解决办法
2万
查看次数

朋友类对象可以在派生类对象上访问基类私有成员吗?

我很惊讶下面的代码编译.

似乎一个与(公共继承)基类成为朋友的类可以访问基类的成员,提供派生类的实例.

如果继承被更改为private则编译失败.

总之,内部如何d.b_var有效F::func(D& d)

#include <iostream>
#include <string>
using namespace std;

class B{
    int b_var;
    friend class F;
};

class D: public B{
    int d_var;
};

class F{
    public:
        void func(D &d){
            d.b_var = 5; 
        }
};

int main()
{
    cout<<"fine";
}
Run Code Online (Sandbox Code Playgroud)

c++ inheritance private friend

12
推荐指数
2
解决办法
2332
查看次数

标签 统计

c++ ×2

inheritance ×2

encapsulation ×1

friend ×1

private ×1

protected ×1