C++ 构造函数错误:需要标识符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20764280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:18:28  来源:igfitidea点击:

Error at constructor : Expected an identifier?

c++oop

提问by Abd Al Rahman Hamdan

I am working with a bunch of classes with composition and I keep getting this error (Expected an identifier) when I try to implement the constructor , here the class header:

我正在处理一堆具有组合的类,当我尝试实现构造函数时,我不断收到此错误(预期的标识符),这里是类头:

#ifndef STUDENT_H_
#define STUDENT_H_

#include "University.h"
class Student {
public:
    Student(); // constructor
    friend ostream & operator<<(ostream &, Student &); // print the student data
    friend istream & operator>>(istream &, Student &); // to read student data
private:
    const int id; 
    string name; 
    int marks[5];
    Date admissionDate; // Composition
    University university;  // Composition
};

#endif

what do I need to do to solve this error ?

我需要做什么来解决这个错误?

here's the cpp but I still did not implement the other io functions because I want to solve that error first..

这是 cpp,但我仍然没有实现其他 io 函数,因为我想先解决那个错误..

#include "Student.h"
Student::Student(){}
ostream & operator<<(ostream &, Student &){} 
istream & operator>>(istream &, Student &){}

回答by Vlad from Moscow

Your constructor should be defined the following way

您的构造函数应按以下方式定义

Student::Student() { /* some code */ } 

回答by A.E. Drew

Since a Studenthas a const int idmember, you need to initialize it in the constructor's initialization list. E.g.:

由于 aStudent有一个const int id成员,您需要在构造函数的初始化列表中对其进行初始化。例如:

Student::Student() : id(0)
{ }