标准 C++ 类型(例如 int 或 char)具有 ctor,因此您可以使用如下表达式:
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
}