gpt4 book ai didi

c++ - 派生类可以访问作为内部类友元的父类的 protected 内部类的私有(private)方法吗?

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:07 24 4
gpt4 key购买 nike

考虑这个类:

class Matchable
{
protected:
class Match {
friend class Matchable;

void append( const Match& match ) {}
};

public:
virtual bool match( const Source& source ) = 0;
};

...其中外部类 Matchable 是内部类 Match 的友元,并且考虑这个类:

class Literal : public Matchable {

bool match( const Source& source ) override {
Matchable::Match m;
Matchable::Match cm;

m.append( cm );

return true;
}

}

...其中 Literal 派生自 Matchable,我似乎可以在 Literal 中实例化 Matchable::Match::match() 没有问题,但我无法调用私有(private)方法 Matchable::Match::append(),而我期望的是 Literal继承Matchable的“友好性”。

这是预期的行为吗?如果是,是否有办法让 Literal 访问其父内部类 Match 的私有(private)方法?

最佳答案

是的,这是预期的行为。参见 friend declaration

Friendship is not inherited (your friend's children are not your friends)

您可以在 Matchable 中提供委托(delegate)方法:

class Matchable
{
protected:
class Match {
friend class Matchable;
void append( const Match& match ) {}
};
void appendMatch( Match& match, const Match& matched ) {
match.append(matched);
}

public:
virtual bool match( const Source& source ) = 0;
};

然后

class Literal : public Matchable {

bool match( const Source& source ) override {
Matchable::Match m;
Matchable::Match cm;

appendMatch(m, cm);

return true;
}

}

否则,您可能会使 Match::append public(这会使友元声明变得毫无意义)。

关于c++ - 派生类可以访问作为内部类友元的父类的 protected 内部类的私有(private)方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com