![](/img/trans.png)
[英]Problem while initializing reference variable of class through Member initialization list
[英]No error for not initializing reference variable of class
我是新手,對對象創建和構造函數之間的關系有基本的疑問。
程序1
#include<iostream>
using namespace std;
class xxx{
private: int x;
public: xxx(){cout<<"constructer is called"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1; //Constructor is called
return 0;
}
輸出構造函數稱為
程式2
#include<iostream>
using namespace std;
class xxx{
private: int x;
public: xxx(){cout<<"constructer is called"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1(); //Constructor xxx() is not called.
return 0;
}
輸出-空白任何信息都非常有幫助
這個:
xxx x1();
是一個函數聲明(稱為x1
函數,不帶任何參數並返回xxx
),而不是變量聲明,因此不會創建xxx
實例(因此不調用構造函數)。
xxx x1;
創建一個類xxx
的對象,因此,調用類xxx
默認構造函數。
xxx x1();
聲明一個函數,該函數返回類xxx
的對象,函數名稱為x1
,不帶參數。 它不是類xxx
的實例,因此,沒有構造函數被調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.