C++ struct 初始化

#include 
#include 
#include 
#include 
using namespace std;

struct A{
    A(){
        cout<<"default constructor"< vec;
};

struct B{
    int n1;
    int n2;
    vector vec;
};

int main()
{
    // A a1{1};//error:  error: no matching function for call to ‘A::A()’
    A a2{1, 2};
    cout<< a2.n1 << " " << a2.n2 << endl; //Ouput: element constructor 1  2
    A a3(1, 2);
    cout<< a3.n1 << " " << a3.n2 << endl; //Ouput: element constructor 1  2
    A* a4 = new A();
    cout<< a4->n1 << " " << a4->n2 << endl; //Ouput: default constructor  0 0
    A* a5 = new A(1, 2);
    cout<< a5->n1 << " " << a5->n2 << endl; //Ouput: element constructor  1 2
    a5->vec.push_back(3);
    cout<< a5->vec.size() << endl; //Ouput: 1 
    
    A a6;
    a6.n1 = 1;
    a6.n2 = 2;
    cout<< a6.n1 << " " << a6.n2 << endl; //Ouput: default constructor  1 2
    
    B b1{1};
    cout<< b1.n1 << " " << b1.n2 << " " << b1.vec.size() << endl; //Ouput:  1 0 0
    return 0;
}

你可能感兴趣的:(C++ struct 初始化)