2011-03-23 24 views
1

可能重複:
Calling the default constuctor
Why is it an error to use an empty set of brackets to call a constructor with no arguments?沒有空的無參構造堆棧創建新的類實例

我想知道是什麼意思,創建一個類的實例使用無參數構造函數。

例如,如果我有一個「A」級,並嘗試創建一個變量,像這樣:

A myVariable() 

我試圖把一個小項目來測試它:

#include <iostream> 

using namespace std; 

class A 
{ 
    public: 
     A(); 
     A(int a, int b); 
    public: 
     int mA; 
     int mB; 
    private: 
     virtual void init(int a , int b); 
}; 

A::A() 
{ 
    cout << "\tA()" << endl; 
    this->init(0, 0); 
} // end of function A::A 

A::A(int a, int b = 0) 
{ 
    cout << "\tA(int a, int b)" << endl; 
    this->init(a, b); 
} // end of function A::A 

void A::init(int a, int b) 
{ 
    cout << "\tInit(int a, int b)" << endl; 
    mA = a; 
    mB = b; 
} // end of function A::init 

int main() 
{ 
cout << "Start" << endl; 
    cout << "A myA0()" << endl; 
    A myA0(); 

    cout << "A myA1" << endl; 
    A myA1; 

    cout << "A myA2(0)" << endl; 
    A myA2(0); 

    cout << "A myA3(0, 0)" << endl; 
    A myA3(0, 0); 

    cout << "Stop" << endl; 
    return 0; 
} 

的輸出看起來像這樣:

Start 
A myA0() 
A myA1 
    A() 
    Init(int a, int b) 
A myA2(0) 
    A(int a, int b) 
    Init(int a, int b) 
A myA3(0, 0) 
    A(int a, int b) 
    Init(int a, int b) 
Stop 

所以它似乎沒有調用任何構造函數。當我嘗試在Visual Studio中瀏覽它時,它會跳過它,因爲它沒有被編譯,當我嘗試打印出變量時,我得到一個未知的外部符號錯誤。

注意:當然,當使用new操作符執行「new A()」時,將使用默認構造函數。

+4

這個問題已經被問了萬次。這只是尋找騙局的問題。 – Jon 2011-03-23 15:39:29

+0

看看這個:http://stackoverflow.com/questions/180172/why-is-it-an-error-to-use-an-empty-set-of-brackets-to-call-a-constructor -with-no – razlebe 2011-03-23 15:41:30

+0

此外,這一個:http://my.apache.org/questions/5300124/calling-the-default-constructor – Jon 2011-03-23 15:41:45

回答

4

語法:

A myA0(); 

不通過調用默認的構造函數創建A類型的變量,而是聲明的函數沒有參數和返回值A。在標籤中查找最令人頭痛的解析或類似的東西。要創建一個局部變量只是做:

A myA0; // no()!!! 

,你必須要知道不同的問題是,從構造稱爲虛擬方法,或析構函數將不使用動態調度。在A構造函數裏面init的調用是A::init通話,即使你是構建從A派生B類型的對象:

struct B : A { 
    void init(int, int) { std::cout << "B::init(int,int)" << std::endl; } 
}; 
int main() { 
    B b;  // will print "\tInit(int a, int b)" from the constructor of `A` 
    b.init(); // will print "B::init(int,int)" 
} 
相關問題