【发布时间】:2012-08-13 12:06:19
【问题描述】:
有这样的课程:
class A {
public:
bool hasGrandChild() const;
private:
bool hasChild() const;
vector<A> children_;
};
为什么不能像这样在方法hasGrandChild()中定义的lambda表达式中使用私有方法hasChild()?
bool A::hasGrandChild() const {
return any_of(children_.begin(), children_.end(), [](A const &a) {
return a.hasChild();
});
}
编译器发出一个错误,指出方法hasChild() 在上下文中是私有的。有什么解决办法吗?
编辑: 看来我发布的代码最初是有效的。我以为是等价的,但是does not work on GCC的代码更像这样:
#include <vector>
#include <algorithm>
class Foo;
class BaseA {
protected:
bool hasChild() const { return !children_.empty(); }
std::vector<Foo> children_;
};
class BaseB {
protected:
bool hasChild() const { return false; }
};
class Foo : public BaseA, public BaseB {
public:
bool hasGrandChild() const {
return std::any_of(children_.begin(), children_.end(), [](Foo const &foo) {
return foo.BaseA::hasChild();
});
}
};
int main()
{
Foo foo;
foo.hasGrandChild();
return 0;
}
似乎this does not work 的完全限定名称存在问题,但this works。
【问题讨论】:
-
闭包类型和你的
A类没有关系,所以自然不能访问A的非公开成员。也不可能,因为它的类型名称是不可知的,所以你甚至不能把它设为friend。 -
只有我还是在 gcc 上有效? ideone.com/333qw
-
@pmr: 是的,它似乎适用于旧 GCC,但不适用于较新的 GCC。
-
@JurajBlaho 它适用于 4.7.1。更新是指 4.8?
-
它在 4.6.2 中对我不起作用。也许这是一个错误。我应该更新。