簡體   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