美文网首页
C++ struct 初始化

C++ struct 初始化

作者: 无善无恶 | 来源:发表于2020-05-26 15:44 被阅读0次
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;

struct A{
    A(){
        cout<<"default constructor"<<endl;
    }
    A(int n1, int n2): n1(n1),n2(n2){
        cout<<"element constructor"<<endl;
    }
    int n1;
    int n2;
    vector<int> vec;
};

struct B{
    int n1;
    int n2;
    vector<int> 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 初始化

      本文链接:https://www.haomeiwen.com/subject/lzhvahtx.html