Bjarne寫道: – 對(duì)于類型T,T()是默認(rèn)值的表示法,由默認(rèn)構(gòu)造函數(shù)定義. 當(dāng)我們不聲明默認(rèn)構(gòu)造函數(shù)時(shí)會(huì)發(fā)生什么?例如
using namespace std;
class date{
int n,m;
public:
int day(){return n;}
int month(){return m;}
};//no default constructor
int main()
{
date any =date();
cout<<any.month()<<endl;
cout<<any.day()<<endl;
return 0;
}
每次運(yùn)行程序時(shí),該程序的輸出為0和0.我沒有聲明任何默認(rèn)構(gòu)造函數(shù)然后為什么會(huì)退出默認(rèn)值,即0?
編輯-
class date{
int n,m;
public:
date (){
m=1;}
int day(){return n;}
int month(){return m;}
};
int main()
{
date any =date();
cout<<any.month()<<endl;
cout<<any.day()<<endl;
return 0;
}
在閱讀答案后,我提供了一個(gè)默認(rèn)構(gòu)造函數(shù),但現(xiàn)在n正在獲取垃圾值但是根據(jù)答案它應(yīng)該為0,因?yàn)閙是任何其他構(gòu)造函數(shù)都無法接觸的,并且它是值初始化,如答案中所述 解決方法: 您看到的行為是為您的班級(jí)定義的.
怎么&為什么行為定義明確?
規(guī)則是: 如果您沒有提供無參數(shù)構(gòu)造函數(shù),則編譯器會(huì)為您的程序生成一個(gè),以防您的程序需要一個(gè). 警告: 如果程序?yàn)轭惗x了任何構(gòu)造函數(shù),則編譯器不會(huì)生成無參數(shù)構(gòu)造函數(shù).
根據(jù)C標(biāo)準(zhǔn),可以通過3種方式初始化對(duì)象:
>零初始化 >默認(rèn)初始化& >值初始化
當(dāng),類型名稱或構(gòu)造函數(shù)初始化程序后跟()時(shí),初始化是通過值初始化.
從而,
date any =date();
^^^
值初始化無名對(duì)象,然后將其復(fù)制到本地對(duì)象中, ??????而:
date any;
將是默認(rèn)初始化.
值初始化為任何構(gòu)造函數(shù)不可及的成員提供零的初始值. 在你的程序中,n和m超出任何構(gòu)造函數(shù)的范圍,因此初始化為0.
回答編輯問題: 在你編輯的情況下,你的類提供了一個(gè)無參數(shù)的構(gòu)造函數(shù)date(),它能夠(并且應(yīng)該)初始化成員n和m,但是這個(gè)構(gòu)造函數(shù)不會(huì)初始化兩個(gè)成員,所以在這種情況下,沒有零初始化需要place和對(duì)象中未初始化的成員具有Indeterminate(任意隨機(jī))值,此外,此臨時(shí)對(duì)象將復(fù)制到顯示show indeterminate成員值的任何對(duì)象.
對(duì)于Standerdese粉絲: 對(duì)象初始化的規(guī)則適當(dāng)?shù)囟x在:
C 03標(biāo)準(zhǔn)8.5 / 5:
To zero-initialize an object of type T means:
— if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;
— if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;
— if T is a union type, the object’s first named data member is zero-initialized;
— if T is an array type, each element is zero-initialized;
— if T is a reference type, no initialization is performed.
To default-initialize an object of type T means:
— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, the object is zero-initialized.
To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized
來源:https://www./content-4-347851.html
|