struct Test {
Test(int n=0) { }
};
你能用这些术语描述以下语句的作用吗?
Test t1;
Test t2();
Test t3 = 3;
Test t4(4);
Test t5 = Test(5);
struct Test {
Test(int n=0) { }
};
Test t1;
Test t2();
Test t3 = 3;
Test t4(4);
Test t5 = Test(5);
当谈论构造函数时,术语默认和隐式具有以下含义:
default constructor is a constructor that can be called with no arguments. It either takes no arguments or has default values for each of the arguments taken.
implicit constructor is a term commonly used to talk about two different concepts in the language, the
implicitly declared constructor which is a default or copy constructor that will be declared for all user classes if no user defined constructor is provided (default) or no copy constructor is provided (copy). That is, a class with no constructors declared by the user has one default constructor implicitly declared.
implicitly defined constructor is a implicitly declared constructor that is used (odr-used1 in the language and for which the compiler will provide a definition.
struct test
{
test(int i = 0) { }
// test(test const&) implicitly declared here
};
struct test2 { }; // implicitly declared: test2(), test2(test2 const&)
int main()
{
test t;
test copy(t); // causes *definition* of the implicitly
// declared copy constructor
test2 t2; // causes *definition* of test2::test2()
test2 copy2(t2); // causes *definition* of test2::test2(test2 const&)
}
简单地说,如果可以不带参数调用构造函数,则该构造函数是默认的。如果用户没有提供构造函数但已经声明或定义,则该构造函数是隐式(ly declared/defined)的。
至于具体情况:
Test t1;
使用默认构造函数Test(int = 0)
,该构造函数不是隐式的。
Test t2();
这是语言的一种奇怪习惯,它声明了一个不带参数并返回Test
对象的函数。
Test t3 = 3;
Test t4(4);
Test(int)
构造函数,但在本例中它不是作为一个默认构造函数。Test t5 = Test(5);
这个例子与Test t3 = 3
相当,唯一的区别是在这种情况下从5
到Test
的转换是显式的。在这个例子中并不重要,但如果构造函数被标记为explicit
,那么这行代码将编译通过,而t3
的情况则会失败。
*) 另一个隐式使用的例子,指的是从3
到Test
的转换在代码中没有明确请求。将其与t5
进行比较,t5
中程序员明确请求了转换:Test(5)
。
Test
,并使用复制构造函数创建t3
。Test(5)
是一个rvalue时,第五个和第三个现在应该是move初始化。 - PuppyT x=a;
的初始化中[...] 称为 复制初始化。 - David Rodríguez - dribeas