标题: 一个类的构造函数的问题,显示声明就编译不过,很奇怪 [打印本页] 作者: 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}'