2012-07-10 81 views
5

可能重複:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?C++繼承錯誤

我有小的代碼示例:

#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()()’ 



} 

但是如果我改變到下面有一個,如果有效的話,

B* b = new B(); 

b->print(); 

爲什麼當我在堆棧上分配對象時不工作?

回答

9

因爲B b();聲明名爲b的函數返回B。只需使用B b;,並指責C++有一個複雜的語法,這使得這種構造很棘手。

4

B b();聲明瞭一個名爲b的函數,它不需要任何東西並返回B。奇怪?嘗試將您的類B重命名爲Int,並將您的「對象」命名爲f。現在它看起來像

Int f(); 

看起來更像是一個功能,不是嗎?

要定義一個缺省構造的對象,您需要:

B b; 

operator new情況下,默認的構造函數可以被稱爲帶或不帶括號:

B* b = new B; 
B* b = new B();