[英]Use of parenthesis or curly braces in C++ constructor initializer list
[英]Parenthesis vs curly braces
#include<iostream>
using namespace std;
class test
{
public:
int a,b;
test()
{
cout<<"default construictor";
}
test(int x,int y):a(x),b(y){
cout<<"parmetrized constructor";
}
};
int main()
{
test t;
cout<<t.a;
//t=(2,3);->gives error
t={2,3}; //calls paramterized constructor
cout<<t.a;
}
输出:-默认construictor4196576参数构造函数2
为什么在上面的示例中,在{}而不是()的情况下调用了参数化构造函数(即使已经调用了默认构造函数)
我添加了一些其他代码来显示实际情况。
#include<iostream>
using namespace std;
class test
{
public:
int a,b;
test()
{
cout << "default constructor" << endl;
}
~test()
{
cout << "destructor" << endl;
}
test(int x,int y):a(x),b(y)
{
cout << "parameterized constructor" << endl;
}
test& operator=(const test& rhs)
{
a = rhs.a;
b = rhs.b;
cout << "assignment operator" << endl;
return *this;
}
};
int main()
{
test t;
cout << t.a << endl;
//t=(2,3);->gives error
t={2,3}; //calls parameterized constructor
cout << t.a << endl;
}
输出:
default constructor
4197760
parameterized constructor
assignment operator
destructor
2
destructor
因此,语句t={2,3};
实际上是使用参数化构造函数构造一个新的test
对象,调用赋值运算符将t
设置为等于新的临时test
对象,然后销毁该临时test
对象。 它等效于语句t=test(2,3)
。
采用
test t(2,3);
代替
test t;
t=(2,3);
因为在对象声明之后使用括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.