標準C++類型,如int或焦有構建函數,這樣就可以有這樣的表達式:通過引用傳遞一個匿名可變
int a = int(67); // create anonymous variable and assing it to variable a
int b(13); // initialize variable b
int(77); // create anonymous variable
用戶定義的類型(結構或類)能夠做同樣的:
struct STRUCT
{
STRUCT(int a){}
};
STRUCT c = STRUCT(67);
STRUCT d(13);
STRUCT(77);
問題是:爲什麼我們可以通過引用匿名結構或類實例傳遞,但不能傳遞標準類型?
struct STRUCT
{
STRUCT(int a){}
};
void func1(int& i){}
void func2(STRUCT& s){}
void func3(int i){}
void func4(STRUCT s){}
void main()
{
//func1(int(56)); // ERROR: C2664
func2(STRUCT(65)); // OK: anonymous object is created then assigned to a reference
func3(int(46)); // OK: anonymous int is created then assigned to a parameter
func4(STRUCT(12)); // OK: anonymous object is created then assigned to a parameter
}
您的'func2'行不應該編譯(出於與第一個相同的原因)。 – Mat
'void main()'是非標準的。 –
在適當的警告級別下,您將得到'警告C4239:使用非標準擴展名:'參數':從'STRUCT'轉換爲'STRUCT&';非const引用只能綁定到左值。你應該使用'/ W4'。 –