繁体   English   中英

C ++预期在“…”令牌异常之前的类型说明符

[英]c++ expected type-specifier before '…' token exception

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

'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文件中,我还有其他例外。

也许试试这个

#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的函数。

暂无
暂无

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

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