c++ - 为什么这段代码不能编译?

标签 c++ class gcc compiler-errors

我遇到过这样的情况:

struct Foo
{
    void Barry() { }
};

struct Bar : private Foo
{
    template <class F> void Bleh(F Func) { Func(); }
};

struct Fooey : public Bar
{
    void Blah() { Foo f; Bar::Bleh(std::bind(&Foo::Barry, &f)); }
};

而且它无法编译 (g++ 4.7.3)。有错误:

test.cpp: In member function ‘void Fooey::Blah()’:
test.cpp:4:1: error: ‘struct Foo Foo::Foo’ is inaccessible
test.cpp:15:23: error: within this context
test.cpp:4:1: error: ‘struct Foo Foo::Foo’ is inaccessible
test.cpp:15:47: error: within this context

但是,如果我这样做:

class Fooey;
void DoStuff(Fooey* pThis);

struct Fooey : public Bar
{
    void Blah() { DoStuff(this); }
};

void DoStuff(Fooey* pThis)
{
    Foo f;
    pThis->Bleh(std::bind(&Foo::Barry, &f));
}

它编译得很好。这背后的逻辑是什么?

最佳答案

这里

struct Fooey : public Bar
{
    void Blah() { Foo f; Bar::Bleh(std::bind(&Foo::Barry, &f)); }
};

Foo 的名称查找找到 Bar 的基类,这是不可访问的,因为 Bar 是私有(private)继承的。

要修复它,请完全限定名称:

    void Blah() { ::Foo f; Bar::Bleh(std::bind(&::Foo::Barry, &f)); }

关于c++ - 为什么这段代码不能编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18387422/

相关文章:

C++11 线程等待行为:std::this_thread::yield() 与 std::this_thread::sleep_for( std::chrono::milliseconds(1) )

C++ 在所需大小未知时使用内存中的空间

c++ - 如何在没有未定义行为的情况下进行双 block 添加?

c++ - 如何从类里面返回 char*?

gcc - std::complex 乘法非常慢

C++ 异常、GCC 和 "inline-functions"标志

c++ - 函数的完美哈希函数生成器

java - 我应该把不用的方法留在类里面吗?

php - 将 __DIR__ 常量与字符串连接作为数组值,它是 PHP 中的类成员

gcc - 由GCC创建的exe文件没有权限?