[英]What is the difference between the different declarations methods in C++?
以下声明有什么区别?
C c1 {C(42)};
C c2 (C(42));
C c3 {7};
C c4 = {7};
C c5 (7);
其中 C 是:
struct C {
int x;
C(int n): x{n} {};
C(const C &c) {x=c.x;};
};
将调用哪个构造函数,或者是否会创建一些临时的 object?
让我们对您的结构做一个简单的更改,以便它打印正在调用的构造函数:
struct C {
int x;
C(int n): x{n} { cout << "calling C(int n) \n"; };
C(const C &c) { x=c.x; cout << "calling C(const C &c) \n"; };
};
C c1 {C(42)};
C c2 (C(42));
C c3 {7};
C c4 = {7};
C c5 (7);
// output:
// calling C(int n)
// calling C(int n)
// calling C(int n)
// calling C(int n)
// calling C(int n)
C c6(c1); // this one uses the copy constructor
// output:
// calling C(const C &c)
C c1 {C(42)};
// not sure this works
C c2 (C(42));
// calls the constructor of C with 42 and then copies the object that temporary created to the c2
// object b calling the copy constructor of C
C c3 {7};
// not sure this works
C c4 = {7};
// not sure this works
// it should be and array like :
// C c4[] = {C(7)} ;
// to create and array of objects with initialized values ( C ( 7 ) )
C c5 (7);
// will create c5 with initialized value x = 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.