【问题标题】:c++ expected type-specifier before '…' token exception'...'标记异常之前的c ++预期类型说明符
【发布时间】:2016-01-15 04:19:18
【问题描述】:

我有这个代码,它给了我这个错误:

“ToolongString”标记之前的预期类型说明符。

#include <iostream>
#include "student.h";
#include <exception>

using namespace std;

int main()
{
    student stud1;
    int a,b;
    string c,d;
    cout<<"Enter the First Name"<<endl;
    cin>>c;
    try
    {
        stud1.setFirstName(c);
        cout<<"Family Name: "<<stud1.getFirstName()<<endl;
    }
    catch (ToolongString ex1)//error
    {
        cout<< ex1.ShowReason() <<endl;
    }
     return 0;
  }

这是 TooLongString 类:

class ToolongString{
public:

    char *ShowReason()
    {
        return "The name is too long";
    }

};

我有一个这样的班级学生的头文件:

#ifndef STUDENT_H
#define STUDENT_H
#include <string>
#include <iostream>


using namespace std;

class student
{

 public:
    student();
    virtual ~student();
    int studentId,yearOfStudy;
    string firstName,familyName;

    void setFirstName(string name);
    void setFamilyName(string surname);
    void setStudentId(int id);
    void setYearOfStudy(int year);
    string getFirstName();
    string getFamilyName();
    int getStudentId();
    int getYearOfStudy();
    };
    #endif /

在 student.cpp 文件中,我还有其他类似的例外情况。

【问题讨论】:

  • 您没有向我们展示完整的源文件,但我没有看到 } 的结束 main
  • 可能编译器在您尝试捕获它时不知道类 ToolongString。您需要在 main 之前声明它,可能在头文件中。
  • ShowReason 函数自 C++11 起是非法的,它应该返回 char const *
  • 抱歉信息不正确。现在我添加了除了 student.cpp 文件之外的所有内容

标签: c++ exception


【解决方案1】:

不妨试试这个

#include <iostream>
using namespace std;

class ToolongString{
public:

    char const *ShowReason()  // Changed return type to const
    {
        return "The name is too long";
    }

};

int main()
{
    string c;
    cout<<"Enter the First Name"<<endl;
    cin>>c;
    try
    {
        if (c.length() > 10) throw(ToolongString()); // Max 10 chars allowed or it throws

        cout<<"Family Name: "<<c<<endl;  // Okay - print it
    }
    catch (ToolongString& ex1)   // Change to & (reference)
    {
        cout<< ex1.ShowReason() <<endl;
    }
}

在 ideone.com 上试试 - http://ideone.com/e.js/uwWVA9

编辑 由于评论

您不能只将 ToolongString 类放在 student.cpp 中。您必须在 student.h 中声明/定义它,以便编译器在编译 main 时知道它。将课程放在 student.h 中。

每个 cpp 文件都是在不知道其他 cpp 文件的内容的情况下编译的。因此,您必须向编译器提供编译 cpp 文件所需的所有信息。这是通过在 h 文件中声明事物(类)然后在相关的地方包含 h 文件来完成的。实现可以保存在 cpp 文件中,但如果您愿意,也可以将(类的)实现放入 h 文件中。

在您的情况下,您需要(至少)告诉编译器您有一个名为 ToolongString 的类,并且该类有一个名为 ShowReason 的函数。

【讨论】:

  • 你改变了什么?如何以及为什么?
  • @JavierMuhlach - 你有 ToolongStringmain 之前声明的类吗?
  • 在主要之前我什么都没有。我在 student.cpp 文件中声明的 ToolongString 类
  • @JavierMuhlach - 那么你需要在 student.h 中声明这个类。在编译main 时,编译器需要知道ToolongString 的外观。您不能将其隐藏在 cpp 文件中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
相关资源
最近更新 更多