簡體   English   中英

沒有初始化類的引用變量沒有錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM