标准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'。 –