0

C++11 標準の 7.3.3.p1 と p3 の両方の段落は、コンストラクターを指定するusing 宣言を参照しています。なぜこれが必要なのですか?以下のコードは、基本クラスAのコンストラクターが派生クラスBで期待どおりに表示されることを示しています。

class A
{
    int i;

    public:
    A() : i(0) {}
    A(int i) : i(i) {}
};

class B : public A
{
    public:
//  using A::A;
    A f1() { return A(); }
    A f2() { return A(1); }
};

int main()
{
    B b;
    A a1 = b.f1();
    A a2 = b.f2();
}

上記をコメントアウトしてusing A::A;も、プログラムの実行に変化はありません。

4

1 に答える 1

3

これは、この場合、親クラスからデフォルト以外のコンストラクターを継承するためのものです。A(int i)main の宣言を次のように変更します。

int main()
{
    B b(42);  // Want to forward this to A::A(int)
    ...
}

句がないusing A::Aと、次のコンパイラ エラーが発生します (少なくとも g++ 4.8.0 以降)。

co.cpp: In function ‘int main()’:
co.cpp:20:11: error: no matching function for call to ‘B::B(int)’
     B b(42);
           ^
co.cpp:20:11: note: candidates are:
co.cpp:10:7: note: B::B()
 class B : public A
       ^
co.cpp:10:7: note:   candidate expects 0 arguments, 1 provided
co.cpp:10:7: note: constexpr B::B(const B&)
co.cpp:10:7: note:   no known conversion for argument 1 from ‘int’ to ‘const B&’
co.cpp:10:7: note: constexpr B::B(B&&)
co.cpp:10:7: note:   no known conversion for argument 1 from ‘int’ to ‘B&&’

しかし、宣言を追加しusing A::A直すと、きれいにコンパイルされます。 b(42)を呼び出してしまいA::A(int i)ます。

于 2013-07-08T17:34:35.180 に答える