定义了一个结构体,想定义它的默认值,于使用在里头用上了默认构造函数:
void main(){
typedef struct struct_test{
int i;
char c;
struct_test(){
i = 0;
c = a;
}
}TEST;
//却发现不能在声明的时候赋值
TEST a = {1,b};
}
报错如下: error C2552: a : non-aggregates cannot be initialized with initializer list
但是不用构造函数就没有问题.
有趣的是不用typedef别名的话,使用了构造函数也没有问题.
void main(){
typedef struct test{
int i;
char c;
struct_test(){
i = 0;
c = a;
}
};
test a = {1,b};
}
求教!
void main(){
typedef struct struct_test{
int i;
char c;
struct_test(int j,char d){
i = 0;
c = a;
}
}TEST;
//却发现不能在声明的时候赋值
TEST a(1,c);
}
不能声明是因为你没有对应的构造函数!
void main(){
typedef struct test{
int i;
char c;
struct_test(){
i = 0;
c = a;
}
struct_test(int ii, char cc){
i = ii;
c = cc;
}
};
test a = {1,b};
}
这样就可以了。
增加一个构造函数
好像好多人的构造函数写错了哦,他的结构体名可是test阿,怎么都写成struct_test了???
大家怎么不测试一下自己的程序在帮人解决阿,不觉得这样会误导别人吗?
在MSDN上查一下:“C2552”就知道了......
调试了一下,如果使用了默认构造函数,则必须为struct起个与构造函数相同的名字。
void main(){
typedef struct struct_test{
int i;
char c;
struct_test(){
i = 1;
c = a;
}
}TEST;
//下面使用默认构造函数
// TEST a = {1,b};
TEST a;
cout << "a.i:" << a.i << endl << "a.c:" << a.c << endl;
}
如果不使用默认构造函数,自己赋值,则不必起个相同的名字,但会有一条warning。
void main(){
typedef struct {
int i;
char c;
struct_test(){
i = 1;
c = a;
}
}TEST;
//下面不使用默认构造函数
TEST a = {1,b};
// TEST a;
cout << "a.i:" << a.i << endl << "a.c:" << a.c << endl;
}