我有这段代码,它给了我这个错误:
expected type-specifier before 'ToolongString' token.
#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
的函数。
关于c++预期类型说明符在 '…' token 异常之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34798166/