2012-07-10 8 views
5

可能性の重複:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?C++継承エラーオブジェクトがスタックに割り当てられ

Iが小さなサンプルコードを持っている:

#include <iostream> 

using namespace std; 

class A 
{ 
    public: 

    void print() 
    { 
    cout << "Hello" << endl; 
    } 

}; 

class B: public A 
{ 

    public: 

    B() { cout << "Creating B" << endl;} 

}; 


int main() 
{ 

    B b(); 

    b.print(); // error: request for member ‘print’ in ‘b’, which is of non-class type ‘B()()’ 



} 

私は変更があれば1つ下の場合、それが動作すれば、

B* b = new B(); 

b->print(); 

なぜ私はスタックにオブジェクトを割り当てると機能しませんか?

答えて

9

B b();bという関数が宣言されており、Bを返します。ちょうどB b;を使用して、C++に複雑な文法があることを批判します。

4

B b();は、何も取り込まない関数bを宣言し、Bを返します。驚くべきこと?クラスBの名前をIntと変更し、オブジェクトの名前をfとしてください。今のように見える

Int f(); 

はもっと機能のように見えますか?デフォルト・構築されたオブジェクトを定義するには

、あなたが必要とする:operator newの場合

B b; 

を、デフォルトコンストラクタがでたり、括弧なしで呼び出すことができます。

B* b = new B; 
B* b = new B(); 
関連する問題