![](/img/trans.png)
[英]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.