我有一个必须在其他类 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/