新疆炒米粉的做法视频:C++中“' must have class/struct/union type”是什么错误

来源:百度文库 编辑:中科新闻网 时间:2024/05/06 12:41:52
#include "iostream.h"
#include "stdlib.h"
#include "iomanip.h"
#include "stdio.h"
#include "string.h"
#include "ctype.h"
#include "conio.h"
#include "mem.h"
# define N 70
struct student
{
char num[10];
char name[10];
char classes[7];
float sum;
float aver;
struct score mark;
}a[];
struct score//定义结构体类型变量
{
float mazhe;
float math;
float engl;
float lanc;
float phy;
};

//输入学生成绩:
void add(student a[])
{
cout<<"请您输入学生信息:"<<endl;
cout<<"姓名"<<setw(8)<<"学号"<<setw(8)<<"班级"<<setw(8)<<"马哲"<<setw(8)<<"数学"<<setw(8)<<"英语"<<setw(8)<<"c语言"<<setw(8)<<"物理"<<endl;
for(int i=0;i<N;i++)
{
cin>>a[i].name>>a[i].num>>a[i].classes;
cin>>a[i].mark.mazhe>>a[i].mark.math>>a[i].mark.engl>>a[i].mark.lanc>>a[i].mark.phy;
} //输入学生的姓名、学号、班级、成绩
}

error C2228: left of '.mazhe' must have class/struct/union type

是C++中常见的一种类型使用错误而产生的编译报错:"'.mazhe'的左边必须是类、结构、联合体之一" , 使用点(.)或箭头(->)引用变量时,操作符左边必须是以上三种数据类型的变量才可以

针对本题:

  1. 在使用结构体类型数据时,要先定义结构体变量

  2. 定义结构体变量之前,应该先定义结构体

否则就会出现以上错误。

  1. struct score mark;  //在定义这个结构体变量mark前,struct score还没有定义,因此,会报错: error C2079: 'mark' uses undefined struct 'score' , 因此,系统就会认为,该变量mark未定义

  2. cin>>a[i].mark.mazhe  这里操作时,mark因未定义,系统不知道其类型,因而产生上面开始提到的错误!error C2228: left of '.mazhe' must have class/struct/union type

改正办法:

把struct score的定义提前就可以了,如下:

struct score//定义结构体类型变量  放到该类型变量定义之前
{
float mazhe;
float math;
float engl;
float lanc;
float phy;
};

struct student 
{
char num[10];
char name[10];
char classes[7];
float sum;
float aver;
struct score mark; //这里定义才不会报错
};

就是你类型用错了,又没有进行强制转换,把代码贴出来看吧