C++错误 C2533,ctor :构造函数不允许返回类型

C++ error C2533, ctor : constructors not allowed a return type

本文关键字:构造函数 不允许 返回类型 ctor 错误 C2533 C++      更新时间:2023-10-16

>我有一个叫老师的班级

 class Teacher
{
private:
    int ID;
    string qualification;
    double salary;
    Date DOB;
    Date dateJoined;
public:
    Teacher();
    void setTeacher (int, string, double);
    string getQualification();
    void displayTeacher();
}
//This is my constructor
Teacher::Teacher()
{
     ID = 0;
     qualification =" " ;
     salary=0.0;
}

我收到错误 C2533:"老师::{ctor}":不允许返回类型的构造函数。我哪里做错了?

您没有在类定义后放置分号。

这混淆了解析器,它现在认为你正在编写这样的东西:

 class {}     functionName(args) {}
 ^^^^^^^^     ^^^^^^^^^^^^
return type   constructors
 defined     are functions, but
 in-place     they don't have
  (oops)       return types!
                 (oops)

现代GCC(比如4.9.2)对这个问题非常清楚:

class Teacher
{
    Teacher();
}
Teacher::Teacher()
{}
// main.cpp:3:1: error: new types may not be defined in a return type
//  class Teacher
//  ^
// main.cpp:3:1: note: (perhaps a semicolon is missing after the definition of 'Teacher')
// main.cpp:8:18: error: return type specification for constructor invalid
//  Teacher::Teacher()
//                  ^

(现场演示)