- 论坛徽章:
- 0
|
10可用积分
我有一个小程序,运行没有问题。但是我稍加修改就编译不过了:
> cat t.cpp
#include<stdio.h>
struct e{//结构体有3个成员
int x;
int y;
int z;
e& operator=(const e& ie){*this=ie;}
~e(){}
};
int main(void){
e buf[]={//用两个成员的{}来初始化
{1,2},
{1,3},
{1,4}
};
printf("%d %d %d\n",buf[0].y,buf[1].y,buf[2].y);
return 0;
}
> ./a.out
2 3 4
--------------------------------------------------------------------------------------------
由于e有3个成员,我显示的定义构造/拷贝函数,但是总是出编译错误:
(1)如果我加上默认构造函数 e(){}
> gcc t.cpp
t.cpp: In function `int main()':
t.cpp:19: subobject of type `e' must be initialized by constructor, not by `{1, 2}'
(2)如果我加上拷贝构造函数 e(const e& ie){*this=ie;}
> gcc t.cpp
t.cpp: In function `int main()':
t.cpp:19: subobject of type `e' must be initialized by constructor, not by `{1, 2}'
(3)如果我加上两个参数的构造函数 e(int ix,int iy){}
> gcc t.cpp
t.cpp: In function `int main()':
t.cpp:19: subobject of type `e' must be initialized by constructor, not by `{1, 2}'
--------------------------------------------------------------------------------------------
为什么总是不行呢? gcc默认生成的构造函数为什么就能工作? 我声明的就不行?
实验环境: solaris8 gcc2.95.2(mingWin gcc3.4.2给出的错误类似)
还请dx指点迷津,10分感谢! |
最佳答案
查看完整内容
只有那些没有定义构造函数且所有数据成员全部为public的类,才可以应用C风格的初始化方式(大括号方式),这是为了与C兼容
|