繁体   English   中英

成员必须具有班级/结构/工会

[英]Member must have class/struct/union

我正在尝试编写一个名为student.hC ++类定义,该定义将从用户定义的输入文件中读取成绩,并将成绩写入用户定义的输出文件中。 到目前为止,这是我所遇到的,但是我遇到此错误,而且我不知道如何解决。 我想知道是否有人可以帮助我解决这个问题:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <fstream>
using namespace std;

class student {
private: 
    int id; 
    int n;  // no of- grades
    int A[200]; // array to hold the grades
public: 
    student(void);              // constructor
    void READ(void);          // to read from a file to be prompted by user;
    void PRINT(void);      // to write into an output file
    void showStudent();   //show the three attributes
    void REVERSE_PRINT(void);      // to write into output file in reverse order;
    double GPA(void);           // interface to get the GPA
    double FAIL_NUMBER(void); //interface to get the number of fails
};



void student::READ()
{

    ifstream inFile;
    ofstream outFile;
            string fileName;
            cout << "Input the name of your file" << endl;
            cin >> fileName;
            inFile.open(fileName.c_str());
            if (inFile.fail()) {
                cout << fileName << "does not exist!" << endl;
            }
            else
            {
                int x;
                inFile >> x;
                while (inFile.good()) 
                {
                    for(int i=0;i<200;i++)
                    {
                        A[i]=x;                 
                    }
                    inFile >> x;
                }
            inFile.close(); 
            }
}

int main()
{
     student a();
     a.READ();     //Line 56

}

这是我在编译代码时得到的语法:

1>------ Build started: Project: New Project, Configuration: Debug Win32 ------
1>  Main.cpp
1>c:\users\randy\documents\visual studio 2012\projects\new project\new project\main.cpp(56): error C2228: left of '.READ' must have class/struct/union
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

这就是所谓的最烦人的解析

student a();
         ^^

这实际上是一个函数声明,您需要的是:

student a;

或者在C ++ 11中,您可以使用统一初始化

student a{};

问题在于C ++语法中存在歧义,因此任何可以解释为函数声明的事物都将是这样。 C ++标准草案中的6.8 模糊度解决方案对此进行了介绍。

这是使用第二个编译器可以提供帮助的情况之一, clang实际上立即发现了问题( 实时示例 ),给出的警告如下:

warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]

 student a();
          ^~

note: remove parentheses to declare a variable

 student a();
          ^~

我在回答在线C ++编译器和评估程序时几乎涵盖了所有在线C ++编译器,并且发现在多个编译器中运行代码具有指导意义。

更新资料

根据您的评论,如果不提供默认构造函数的实现,则会收到错误消息,这是一种实现它的可能方法,但是您需要确定适当的默认值是什么:

student::student() : id(-1), n(0) {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM