标准的C++类型,如int或char,具有构造函数,因此您可以使用以下表达式:
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
行不应该编译(原因与第一行相同)。 - Matvoid main()
是非标准的写法。 - n. m.void main
是错误的。 - Konrad Rudolph