注册 登录
编程论坛 C++教室

[求助]关于结构体数组的问题

boris250 发布于 2007-10-22 19:35, 782 次点击
郁闷的,看的一午的书,再上练习,怎么调试都调不好,不知道哪里出了问题,高手帮忙指点!!!
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
struct Student
{
int num;
char name[10];
char sex;
int age;
float score[3];
}stu[2];
int main()
{
int k;
Student stu;
stu={101,"zhang",'M',19,95.5,64.0};
cout<<stu.num;
return 0;
}
错误提示:
Compiling...
number three.cpp
D:\c++\number three.cpp(17) : error C2059: syntax error : '{'
D:\c++\number three.cpp(17) : error C2143: syntax error : missing ';' before '{'
D:\c++\number three.cpp(17) : error C2143: syntax error : missing ';' before '}'
执行 cl.exe 时出错.

如果将Student stu;
stu={101,"zhang",'M',19,95.5,64.0};
改成Student stu={101,"zhang",'M',19,95.5,64.0};程序就不出错的,不知道这两者有什么区别。
6 回复
#2
aipb20072007-10-22 19:52
那你看书上是用的哪个撒!
Student stu;
stu={101,"zhang",'M',19,95.5,64.0}; //这是赋值



Student stu={101,"zhang",'M',19,95.5,64.0};//这是初始化



虽然他们都是用 “=” 但是意义大不一样了。
#3
风的声音2007-10-22 21:43
结构体不允许这样赋值,但是初始化可以。斑竹已经说出了这两种的不同;
#4
aipb20072007-10-22 22:52
以下是引用风的声音在2007-10-22 21:43:50的发言:
结构体不允许这样赋值,但是初始化可以。斑竹已经说出了这两种的不同;

补充纠正一点:

是没有定义构造函数的非抽象类(所有成员公有)才可以用类似数组模式的初始化。

#5
绝地天使2007-10-24 11:30
stu.num=101;
strcpy(stu.name,"zhang");
stu.sex='M';
stu.score[1]=19;
stu.score[2]=95.5;
stu.score[3]=64.0
#6
duffebear2007-10-24 11:46
最好定义一个构造函数
#7
nuciewth2007-10-24 12:34
结构体可以在定义的时候就给初始化.
既然是弄类的,当然是要有构造函数来初始化一个事例了.
1