4

Visual Studio 2010 を使用しています。

子クラスで public に「アップグレード」されたクラス メソッドへのポインタを取得できないのはなぜですか?

次のコードはコンパイルされません。

#include <iostream>
#include <functional>

class Parent {
protected:
    void foo() {
        std::cout << "Parent::foo()\n";
    }
};

class Child : public Parent
{
public:
    //void foo() { Parent::foo(); } //This compiles
    using Parent::foo; //This does NOT compile
};
int main() {
    Child c;

    std::function < void () > f = std::bind(&Child::foo, &c);
    f();
    return 0;
}

エラーが発生します:

error C2248: 'Parent::foo' : cannot access protected member declared in class 'Parent'
4

4 に答える 4

3

ここにコンパイルされます。

コンパイラに C++11 オプションを追加するのを忘れただけだと思います。

たとえば、gcc の場合は-std=c++11または-std=gnu++11です。

編集:ここから、エイリアス宣言の使用はどのVisual Studioバージョンにも実装されていないようです。

実際、ここで何人かの人々がコンパイラのバグについて語っています。

ここで奇妙なことは次のとおりです。

c.foo();                                                   // this works fine
std::function < void () > f = std::bind(&Child::foo, &c);  // this won't compile
于 2013-09-03T17:10:36.427 に答える
0

c++11 より前では、この 'using' により、次のような場合に Parent::foo を非表示にできません。

class Parent
{
protected:
    void foo() {}
};

class Child : public Parent
{
    using Parent::foo; // without this, following code doesn't compile.
public:
    // foo(int) hides Parent::foo without the 'using'
    void foo(int) { return foo(); }
};
于 2013-09-03T17:33:25.827 に答える
0

このコードは でコンパイルされg++ 4.8.1ます。C++11 を使用していますか? 実行すると、次の出力が得られます。

Parent::foo()
于 2013-09-03T17:08:08.880 に答える