可能重複:
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()」時,將使用默認構造函數。
這個問題已經被問了萬次。這只是尋找騙局的問題。 – Jon 2011-03-23 15:39:29
看看這個: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
此外,這一個:http://my.apache.org/questions/5300124/calling-the-default-constructor – Jon 2011-03-23 15:41:45