Chinaunix

标题: 一个类的构造函数的问题,显示声明就编译不过,很奇怪 [打印本页]

作者: jeanlove    时间: 2009-02-13 18:27
标题: 一个类的构造函数的问题,显示声明就编译不过,很奇怪
我有一个小程序,运行没有问题。但是我稍加修改就编译不过了:
> 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分感谢!
作者: tyc611    时间: 2009-02-13 18:27
只有那些没有定义构造函数且所有数据成员全部为public的类,才可以应用C风格的初始化方式(大括号方式),这是为了与C兼容
作者: jeanlove    时间: 2009-02-13 22:43
原帖由 tyc611 于 2009-2-13 18:41 发表
只有那些没有定义构造函数且所有数据成员全部为public的类,才可以应用C风格的初始化方式(大括号方式),这是为了与C兼容

正确的答案,强有力的答案,给分了!




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2