c++ - c++中的 friend 保护方法

标签 c++ friend-function

我有一个必须在其他类 Bar 中“直接”访问的类 Foo。我想构建一个小框架,声明 Bar 的方法(这是 Foo 的友元方法) protected 。通过这种方式,我可以建立几个 Bar 的子类。

Gcc 对此表示不满,并且它仅在该方法是公开的情况下才有效。

我该怎么办?我的代码示例:

class Foo;
class Bar {
    protected:
        float* internal(Foo& f);
};
class Foo {
    private:
        //some data
    public:
        //some methods
        friend float* Bar::internal(Foo& f);
};

海湾合作委员会消息:

prog.cpp:4:16: error: ‘float* Bar::internal(Foo&)’ is protected
         float* internal(Foo& f);
                ^
prog.cpp:11:43: error: within this context
         friend float* Bar::internal(Foo& f);
                                           ^

最佳答案

很明显,您不能从另一个类访问一个类的 protected /私有(private)成员。如果您尝试与 protected /私有(private)成员函数成为 friend ,情况也是如此。因此,除非将方法放在公共(public)部分或使 Foo 成为 Bar 的友元,否则无法执行此操作。

您也可以通过使整个类 Bar 成为 Foo 的友元来实现此目的。所以要么这样做:

class Bar {
protected:
    friend class Foo; // Foo can now see the internals of Bar
    float* internal(Foo& f);
 };
class Foo {
private:
    //some data
public:
    //some methods
    friend float* Bar::internal(Foo& f);
};

或者这个:

class Bar {
protected:
    float* internal(Foo& f);
};
class Foo {
private:
    //some data
public:
    //some methods
    friend class Bar; // now Bar::internal has access to internals of Foo
};

关于c++ - c++中的 friend 保护方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349904/

相关文章:

C++ 将数组传递给函数

c++ - 如何比较相似的代码库?

c++ - operator== 使用 msvc 编译,但不使用 gcc 和 clang 编译

c++ - 运算符重载: calling friend function from member function

c++ - 好友功能无法访问私有(private)成员

c++ - 关于简单 CPU 仿真器实现的问题

c++ - 将多个元素以多个偏移量插入到 vector 中

c++ - Friend 成员函数可以在单独的文件中使用吗?

c++ - Clang:类中定义的友元函数

c++ - 如何修复此错误访问冲突读取位置 0x00000008