#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 初始化
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...