成员必须具有class/struct/union

1 c++ syntax

我正在尝试编写一个C++类定义student.h,该类定义将从用户定义的输入文件中读取等级,并将等级写入用户定义的输出文件中.这是我到目前为止,但我收到此错误,我不知道如何解决它.我想知道是否有人可以帮我解决这个问题:

#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

}
Run Code Online (Sandbox Code Playgroud)

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

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 ==========
Run Code Online (Sandbox Code Playgroud)

Sha*_*our 6

这就是所谓的最令人烦恼的解析:

student a();
         ^^
Run Code Online (Sandbox Code Playgroud)

这真的是一个函数声明你需要的是这个:

student a;
Run Code Online (Sandbox Code Playgroud)

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

student a{};
Run Code Online (Sandbox Code Playgroud)

问题是C++语法存在歧义,因此可以解释为函数声明的任何东西都是.这是覆盖在部分6.8 模糊度解算草案C++标准.

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

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

 student a();
          ^~

note: remove parentheses to declare a variable

 student a();
          ^~
Run Code Online (Sandbox Code Playgroud)

在我对在线C++编译器和评估器的回答中,我几乎涵盖了所有在线C++编译器,我发现在多个编译器中运行代码是有指导意义的.

更新

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

student::student() : id(-1), n(0) {}
Run Code Online (Sandbox Code Playgroud)

  • @ H2CO3实际上我问斯科特在电子邮件中澄清他是否认为这属于MVP并且他说他做了.我知道很多人在SO上感觉不然但是在重读了那段*有效的STL*后我感觉它实际上是另一个MVP案例,所以我通过电子邮件发送并询问. (2认同)