Reputation: 11
I have this code and it gives me this error:
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;
}
and this is the TooLongString class:
class ToolongString{
public:
char *ShowReason()
{
return "The name is too long";
}
};
and I have a header file of the class student like this:
#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 /
In the student.cpp file a I have other exceptions like that one.
Upvotes: 0
Views: 4856
Reputation: 44274
Maybe try this
#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;
}
}
Try it at ideone.com - http://ideone.com/e.js/uwWVA9
EDIT due to comment
You can't just place the class ToolongString
inside student.cpp. You must declare/define it in student.h
so that the compiler knows it when compiling main. Put the class in student.h instead.
Each cpp file is compiled without knowing the contents of other cpp-files. Therefore you must to give the compiler all the information it needs to compile a cpp-file. That is done by declaring things (classes) in h-files and then include the h-files where relevant. The implementation can be kept in a cpp-file but you can also put the implementation (of classes) in the h-file if you like.
In your case you need (at least) to tell the compiler that you have a class named ToolongString
and that the class has a function named ShowReason
.
Upvotes: 1