括号与花括号

uni*_*ver 0 c++ constructor

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出: - 默认constructor4196576parmetrized constructor2

为什么在上面的例子的情况下,参数化的构造函数(即使已经调用了默认构造函数.)在{}而不是在()的情况下被调用.

Dav*_*ett 5

我添加了一些额外的代码来显示实际发生的情况.

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

default constructor
4197760
parameterized constructor
assignment operator
destructor
2
destructor
Run Code Online (Sandbox Code Playgroud)

因此,该语句t={2,3};实际上是test使用参数化构造函数构造一个新对象,调用赋值运算符设置t为等于新的临时test对象,然后销毁临时test对象.它等同于声明t=test(2,3).