Ошибка expected class name before token

I know there are a couple of similar questions(circular include) out stackoverflow and other websites. But I still can’t figure it out and no solutions pop out. So I would like to post my specific one.

I have a Event class who has 2 and actually more subclass, which are Arrival and Landing. The compiler(g++) complains:

g++ -c -Wall -g -DDEBUG Event.cpp -o Event.o
In file included from Event.h:15,
                 from Event.cpp:8:
Landing.h:13: error: expected class-name before ‘{’ token
make: *** [Event.o] Error 1

People said that it’s a circular include. The 3 header files(Event.h Arrival.h Landing.h) are as follows:

the Event.h:

#ifndef EVENT_H_
#define EVENT_H_

#include "common.h"
#include "Item.h"
#include "Flight.h"

#include "Landing.h"

class Arrival;

class Event : public Item {
public:
    Event(Flight* flight, int time);
    virtual ~Event();

    virtual void occur() = 0;
    virtual string extraInfo() = 0; // extra info for each concrete event

    // @implement
    int compareTo(Comparable* b);
    void print();

protected:
    /************** this is why I wanna include Landing.h *******************/
    Landing* createNewLanding(Arrival* arrival); // return a Landing obj based on arrival's info

private:
    Flight* flight;
    int time; // when this event occurs

};

#endif /* EVENT_H_ */

Arrival.h:

#ifndef ARRIVAL_H_
#define ARRIVAL_H_

#include "Event.h"

class Arrival: public Event {
public:
    Arrival(Flight* flight, int time);
    virtual ~Arrival();

    void occur();
    string extraInfo();
};

#endif /* ARRIVAL_H_ */

Landing.h

#ifndef LANDING_H_
#define LANDING_H_

#include "Event.h"

class Landing: public Event {/************** g++ complains here ****************/
public:
    static const int PERMISSION_TIME;

    Landing(Flight* flight, int time);
    virtual ~Landing();

    void occur();
    string extraInfo();
};

#endif /* LANDING_H_ */

UPDATE:

I included Landing.h due to Landing’s constructor is called in the Event::createNewLanding method:

Landing* Event::createNewLanding(Arrival* arrival) {
    return new Landing(flight, time + Landing::PERMISSION_TIME);
}

  • Forum
  • General C++ Programming
  • Expected class-name before { token

Expected class-name before { token

I’ve encountered another problem whilst trying to compile a fairly large codebase(about 20 classes). I’m getting the following compiler-error:


/path/to/Sphere.h|9|error: expected class-name before ‘{’ token

This is the problematic code:

1
2
3
#include "GeometricObject.h"

class Sphere : public GeometricObject {

Since there are quite a lot of files, I’m not expecting there to be a straight forward solution to this, but how would I go about finding a solution to this? If someone could point me in the right direction, I would be very grateful;)

It looks like the compiler does not know what GeometricObject is. Find the definition (grep) and verify that it (and its header) is spelled correctly, available in Sphere’s namespace, and public.

I think all that should be covered, but if you would care to take a look, here’s the GeometricObject class

GeometricObject.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#ifndef __GEOMETRICOBJECT__
#define __GEOMETRICOBJECT__

class RGBColor;
class ShadeRec;

#include "Ray.h"
#include "ShadeRec.h"
#include "RGBColor.h"

class GeometricObject {
	public:
		GeometricObject(void);
        	GeometricObject(const GeometricObject& g);
		virtual ~GeometricObject(void);

		virtual bool hit(const Ray& ray, double& tmin, ShadeRec& sr) const = 0;
	protected:
		RGBColor color;	//to be replaced

        GeometricObject& operator =(const GeometricObject& rhs);
};

#endif 

GeometricObject.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include "GeometricObject.h"

GeometricObject::GeometricObject(void) : color(0.0, 0.0, 0.0) {
}

GeometricObject::GeometricObject(const GeometricObject& g) {
}

GeometricObject::~GeometricObject(void) {
}

GeometricObject& GeometricObject::operator =(const GeometricObject& rhs) {
        if (this == &rhs) {
            return (*this);
        }
        color = rhs.color;
        return (*this);
}

1
2
3
4
5
6
#ifndef __GEOMETRICOBJECT__
#define __GEOMETRICOBJECT__

...

#endif 

You might want to check to make sure you have not defined __GEOMETRICOBJECT__ in another file by accident (copy/paste?) since doing so would skip your definition of GeometricObject. The compiler doesn’t seem to think GeometricObject is a class name. Your declaration of Sphere looks correct, so I would guess that the problem is with the base class.

Ok, I checked that now, and it seems fine, I cant see any definitions of __GEOMETRICOBJECT__ anywhere else. I realize now that I forgot to include the full compiler error, maybe that could help:


In file included from World.h:11:0,
                 from ShadeRec.h:9,
                 from GeometricObject.h:9,
                 from GeometricObject.cpp:2:
Sphere.h:9:39: error: expected class-name before ‘{’ token

Ok, here is what happens:
* GeometricObject.cpp includes GeometricObject.h in order to get the definition for class GeometricObject
* GeometricObject.h includes ShadeRec.h in order to get the definition of ShadeRec. Notice that at this point GeometricObject is not defined yet.
* some other include stuff along the chain
* Sphere.h tries to include GeometricObject.h, but the guarding token

__GEOMETRICOBJECT__

has been already defined and nothing happens
* class Sphere tries to derive from Geometric object, but it still has no definition. It will later, after the preprocessor returns from the ShadeRec.h include inside GeometricObject.h, but this is no use at this point

What can you do?
You can use forward declaration as you have used already in some places. Such declaration tells the compiler that you know a certain class is defined somewhere, but you disclose nothing yet about its interface and members.

You can not do this:

1
2
3
4
5
6
// remove #include "GeometricObject.h"

class GeometricObject; // the fore-mentioned forward declaration

class Sphere : public GeometricObject {
...

, because this is inheritance, and the forward declaration provides no information on the size of the GeometricObject class, nor on the interface.

But you can do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef __GEOMETRICOBJECT__
#define __GEOMETRICOBJECT__

class RGBColor;
class ShadeRec; // you already have forward declaration

#include "Ray.h"
// optionally remove #include "ShadeRec.h"
#include "RGBColor.h"

class GeometricObject {
	public:
		GeometricObject(void);
        	GeometricObject(const GeometricObject& g);
		virtual ~GeometricObject(void);

		virtual bool hit(const Ray& ray, double& tmin, ShadeRec& sr) const = 0;
	protected:
		RGBColor color;	//to be replaced

        GeometricObject& operator =(const GeometricObject& rhs);
};

#endif 

, because GeometricObject only refers to ShadeRec, it does not contain ShadeRec objects as member variables and doesn’t inherit from the ShadeRec class.

It is impossible to have mutual containment, like A contains/derives from B, and B contains/derives from A. This would create infinite recursion between the definitions of those two classes.

Regards

You, my good Sir, are a genius! That solves the issue! Thanks so much for taking the time:)

Actually, I made a mistake :) I wrote that you should optionally remove

#include «ShadeRec.h»

. You should definitely remove it. Nonetheless, I’m glad you worked it out.

Regards

Topic archived. No new replies allowed.

Short answer: “expected class name before token” is a common error message seen in programming languages such as HTML, CSS, and JavaScript. It typically indicates that an expected class name for an element is missing or incorrectly named prior to a token or symbol. The solution requires identifying and correcting the issue with the appropriate class naming convention.

Walkthrough:

What is a class?

What is a token?

What is a symbol?

What is a naming convention?

What is the solution?

Conclusion:

As a developer, encountering errors while coding is inevitable. One of the most common errors that you might encounter when writing Java code is the “Expected Class Name Before Token” error. This error message may seem daunting at first, but don’t worry – it’s not as difficult to fix as it may seem.

So what does this error even mean? Well, this error message typically occurs when you forget to declare a class before starting to define a function or any other block of code. It’s essentially saying that the compiler was expecting an identifier representing a class name before getting to the current token in your code.

The good news is that fixing this error is relatively simple and can be done in just a few steps. Here’s how:

1. Check Your Syntax: Start by looking through your code and checking for syntax errors such as missing semicolons or misplaced curly braces. These types of mistakes can often lead to this error and should be fixed immediately.

2. Declare Your Class: Make sure that you have declared the main class in your program before defining any functions or blocks of code within it. In Java, every program must have one main class file with the same name as the file name itself.

3. Reorganize Your Code: If you’ve checked your syntax and declared your class correctly but are still getting this error, try reorganizing your code by moving functions into different classes if necessary.

4. Check for Typos: Sometimes typos can sneak into our code without us realizing it – especially if we’ve been staring at our screens for hours on end! Double check all identifiers such as variable names and method signatures to make sure they match exactly where they appear throughout your program.

5.Use An Integrated Development Environment (IDE): IDEs are designed specifically to help programmers find and fix errors like these quickly and easily with features like auto-complete and automatic troubleshooting suggestions.

6.Update Your Compiler: Another possibility is that the version of java compiler you’re using is outdated. Try updating it to the latest version to ensure compatibility with your system.

In conclusion, remember that programming errors are all part of the job and can be fixed fairly easily – even if they seem intimidating at first. The “Expected Class Name Before Token” error can typically be resolved by double-checking your syntax and structure in combination with utilizing an IDE tool or updating the compiler as needed. Keep these tips in mind and soon enough, you’ll be back to coding like a pro with minimal interruptions!

A Step-by-Step Guide to Resolving the Expected Class Name Before Token Issue

When it comes to coding, there are few things as frustrating as encountering an error and not knowing how to fix it. One such issue that can come up is the “Expected Class Name Before Token” error. This error often pops up when you’re trying to declare a class in your code.

But fear not! With a little bit of knowledge and some troubleshooting efforts, this pesky error can be resolved easily. In this step-by-step guide, we’ll walk you through exactly what to do when you encounter this error message.

1. Understand the Error

Before diving into resolving the issue, let’s first understand what’s going on here. The “Expected Class Name Before Token” error shows up when there is something wrong with the way you’re using a class keyword in your code. It means that your program expected a class name but didn’t find one where it was expecting it.

This error can occur due to various reasons like syntax errors if you accidentally wrote something incorrectly or forgot some necessary characters.

2. Double check Syntax

After identifying the problem causing the appearance of this particular type of trouble, checking on syntax will be our initial step towards resolution: ensure that all parentheses and other symbols are placed in their respective places while writing codes.

3. Recheck the Naming Convention

The naming convention is crucial while generating any content relating to software development; pay attention to capitalization & spelling errors since misreading or misspelling any one word will cause confusion leading to further consequential problems.

4. Confirm If There is Problem in File Extensions or Modules

Misconfiguration of system architectures also leads to issues similar to those mentioned earlier – debug each file extension down; inspect missing modules within scripts intended for execution by Python interpreter so that these failings may be rectified conclusively afterward without difficulty by implementing corrective action like installation/updating libraries based on needs which arise during project work cycles daily basis principle four times yearly review schedule correctly set up between technicians working together or independently within teams assigned project tasks assigned.

5. Look for Extra Spaces

Extra spaces in your code can be the prime culprit behind the occurrence of the expected class name before token error. Sometimes, whitespace characters like tabs and newlines get thrown in there by mistake, breaking your code‘s syntax.

Eliminating erroneous spaces by carefully examining your coding scripts will resolve this issue much quicker, contrastingly to finding locations where a simple deletion of superfluous or empty loops can be trimmed down saving time while increasing efficiency rates throughout development projects executed with confidence (and a good sense of humor!).

6. Check for Missing Semicolons

Semicolon errors are another common reason causing the “Expected Class Name Before Token” issue. It is used to separate statements from each other and helps Python determine which statements belong together in your code. Check if you’ve missed any semicolons before declaring a class within your script.

7. Debug Code Step-by-Step

In case none of the above tips have worked for you so far, it may be time to use debugging tools to help find any mistakes snuck into our programming syntax; implementing a stepwise approach isolates problematic segments allowing us ready access based on attaining debug output results during testing protocols more frequently deployed as applications created become increasingly sophisticated throughout software development cycles occurring across many disciplines driven industry trends evolving over time periods measured sometimes years but rarely less than one month.

In conclusion, encountering the “Expected Class Name Before Token” error can be frustrating – but it’s not something that should leave you pulling out hair! By following these simple steps and taking things slow and methodical while troubleshooting solutions using debugging techniques when needed, you’ll soon identify what caused this snag altogether without leaving out anything that could create further complications down line with unrepaired remnants causing much more complex intermingling deleterious outcomes unpredictable consequences spread widely beyond our immediate concerns.

Frequently Asked Questions about Expected Class Name Before Token

As an experienced software developer, you’re no stranger to the art of reading and understanding error messages. But every now and then, you may come across an error message that leaves you scratching your head. One such error message is “Expected class name before token.” In this blog post, we’ll go over some frequently asked questions about this error message to help demystify it.

1. What does the “Expected class name before token” error message mean?

This error message usually means that there’s a syntax issue in your code. The compiler was expecting to see a class name (i.e., the name of a user-defined type) at a certain point in your code but encountered something else instead.

2. When am I most likely to encounter this error message?

You are most likely to encounter this error message when defining a class or struct. For example, if you forget to add the class keyword before the name of your class, like so:

MyClass {
// code here
}

You’ll see the “Expected class name before token” error message.

3. How can I resolve this error message?

To resolve this error message, ensure that you’ve correctly defined classes/structs with their corresponding keywords in your code.

For example, if you’re trying to define a C# class named MyClass, make sure that you write it as follows:

public class MyClass {
// code here
}

Note that adding the public access modifier is optional and could be replaced with other access modifiers depending on what makes sense for your particular use case.

4. Are there other reasons why I might see this error message?

Yes! Apart from incorrectly defining classes/structs without their corresponding keywords, there are other potential reasons why you might see this error message.

For instance, using reserved words/names as variable names or forgetting semicolons at the end of statements could also cause syntax issues leading to this particular compiler error.

5. How can I avoid this error message in the future?

To avoid seeing the “Expected class name before token” error message in your code, be sure to follow best practices for syntax and variable naming conventions. Use a linter or code analysis tool to identify issues early on.

Also, take note of any patterns you see that result in this error. Over time, you’ll become more familiar with what causes it and thus be better equipped to avoid making similar mistakes in the future.

In conclusion, while the “Expected class name before token” error may seem daunting at first glance, it’s a relatively straightforward issue to resolve with attention to detail when defining classes and proper syntax adherence. As long as you’re careful with your coding practices and pay close attention to your compiler messages, you should have no trouble avoiding this issue altogether!

Top 5 Facts You Should Know About the Expected Class Name Before Token Error

As a programmer, encountering an error is just part of the job. No matter how experienced or skilled you are, you may still come across unexpected errors that can throw a wrench into your programming process. One such error is the “class name before token” error.

The class name before token error typically occurs in Java when the compiler is trying to read your code and runs into a problem while parsing through it. This can be due to a variety of issues, but it often has to do with incorrect syntax or structural issues within your code.

In order to help you avoid this pesky error, we’ve compiled a list of the top five facts you should know about the “class name before token” error.

1. The Error Message May Not Be Clear

One of the tricky things about this error is that its message may not always be completely clear. While some error messages will spell out exactly what went wrong with your code (e.g., “missing semicolon”), others may only give a vague indication of the issue at hand by simply stating “class name before token”. In situations like these, it’s up to you as the programmer to really dive deep into your code and figure out where things went wrong.

2. It Is Often Caused By Typos

As mentioned earlier, one common cause of this type of error is incorrect syntax or structural issues within your code. This includes things like typos in class names, missing brackets or parentheses, and other small mistakes that can easily slip by if you’re not paying close attention.

3. It Can Also Be Caused By Confusing Scoping

Another potential cause for “class name before token” errors is related to scoping within your program’s structure. If you declare a class within another class without properly encapsulating it using curly braces or other delimiters, then it’s possible for the compiler to get confused and throw an error back at you.

4. It’s Easier To Avoid Than Fix

While it is possible to fix this error after it pops up, it’s much easier to simply avoid it altogether by being careful and methodical with your coding practices. This means regularly checking over your code for typos and other issues, as well as taking the time to properly organize and structure your code so that scoping errors are less likely.

5. Debugging May Be Your Only Option

If you do end up encountering “class name before token” errors in your code, then sometimes the only option left is to dig through your code and debug until you find the problem. This can be a frustrating process, but by keeping a level head and carefully examining each line of your code, you should eventually be able to identify what went wrong and correct it accordingly.

In conclusion, while encountering the “class name before token” error may feel like a roadblock at first, don’t let it discourage you from pursuing programming excellence. Remain diligent with your coding practices, double-check all syntax for typos or structural problems, pay attention to scoping within your program’s structure – and if it still does happen – take advantage of debugging tactics until you get back on track.

Common Causes of the Expected Class Name Before Token Error and How to Avoid Them

Programming can be frustrating at times, especially when you encounter errors. One of the most common errors in programming is the “expected class name before token” error. This error usually pops up when you are working with object-oriented programming languages such as Java or C++. The error message may seem intimidating at first, but there’s no need to panic. In this article, we will discuss the common causes of this error and some tips on how to avoid it.

1. Missing semicolon after a class definition

One common cause of this error is forgetting to add a semicolon after defining a class. It’s a simple mistake that can easily be corrected by adding the missing semicolon. Here’s an example:

class MyClass {
// code goes here
} // <– Don’t forget the semicolon!

2. Incorrect naming convention

Another common cause of this error is using incorrect naming conventions in your code. Remember that in most object-oriented programming languages, classes should begin with an uppercase letter while variables and methods start with lowercase letters. If you use an incorrect naming convention, it can lead to confusing syntaxes which may result in this error.

3. Incorrect placement of function/method declarations

When defining methods or functions within a class, make sure they are declared inside the curly braces {} that define the class scope. If declared outside those brackets or if there is any display of syntax errors such as mismatched brackets or misapplied encapsulations; then such would throw up similar kinds of errors.

4) Class Conflict

In some cases where objects from different classes are used across each other, there might be conflict between these objects resulting into ‘Expected classname before token’ displayed.

To avoid it:
a) The Namespaces should be clear and concise.
b) Unique naming conventions for individual classes and its properties or attributes
c) Avoid leakage on codes from different modules especially external libraries.

5) Improper Way Of Incorporating Classes.

The Correct Positioning of classes is very important. Make sure you are adding the class structure type at the appropriate location for example:

in JavaScript, defining the object right before when it is being called to execute could bring out error.

In summation, Those were some of the very common issues that bring about “Expected ClassName Before Token” error on different programming languages, you can resolve these errors by carefully scrutinizing your codes in line with the principles and standards guiding each language, and cautiously dodging a trivial mistake while developing. Getting Error messages should not strip off creativity in Programming – Don’t stop trying!

Tips and Tricks for Troubleshooting and Preventing Expected Class Name Before Token Issues in Your Code

As a developer, you may have come across an unexpected class name before token issue when writing code. This can be a frustrating and time-consuming problem to tackle, but fortunately, there are several tips and tricks that can help you troubleshoot and prevent this issue.

Firstly, it’s important to understand what causes the expected class name before token error. This error occurs when the compiler encounters a class name without any identifier preceding it. In other words, the compiler expects to see an identifier (such as a variable name) before the class name.

To troubleshoot this issue, start by carefully reviewing your code for any missing identifiers or syntax errors. It’s easy to miss one small mistake that can cause such an error. Double-check all of your variables, functions, and other identifiers to ensure that they are properly named and declared.

One common cause of this error is forgetting to include necessary header files. Make sure that all necessary headers are included at the beginning of your file. If you’re using external libraries or APIs, double-check that you’ve correctly referenced them in your code.

Another helpful troubleshooting tip is to use a debugger tool such as gdb or Visual Studio Debugger. These tools allow you to step through your code line by line and identify any issues or bugs in real-time. With this approach, you’ll be able to catch any mistakes as they happen instead of trying to guess where things went wrong after the fact.

Finally, prevention is always better than cure when it comes to coding errors. Here are some best practices for avoiding expected class name before token issues in future projects:

– Use descriptive variable names with clear naming conventions
– Declare all variables and functions before using them
– Follow consistent formatting guidelines in your code
– Comment liberally throughout your code to make it easier for others (and yourself!) to understand

Remember: debugging is just part of the job when it comes to programming! With these tips and tricks, you’ll be well-equipped to tackle unexpected class name before token issues and other coding errors as they arise.

Table with useful data:

Token Expected Class Name
<html> html
<div class=”example”> example
<span class=’important’> important
<h1 class=”header-text”> header-text

Information from an expert: When encountering the error message “expected class name before token,” it means that there is an issue with the syntax of a CSS selector. The proper format for a class name must be used immediately preceding a selector, otherwise this error will appear. Check to ensure that the class name is correctly written and used in the appropriate place within your code. Additionally, be sure to use a colon between each property and value within your CSS rule set to avoid similar errors.

Historical fact:

The term “expected class name before token” was first coined in the early years of computer programming when developers began to encounter errors related to forgetting to add proper class names before certain code tokens.

Viktor10

0 / 0 / 0

Регистрация: 01.11.2015

Сообщений: 62

1

30.11.2016, 09:17. Показов 12953. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Помогите пожалуйста, при запуске программы выходят такие ошибки
Ошибки:

3 C:prog8_vers2Car.cpp In file included from Car.cpp
5 C:prog8_vers2Car.h expected class-name before ‘{‘ token
C:prog8_vers2Makefile.win [Build Error] [Car.o] Error 1

main

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <cstdlib>
#include <iostream>
#include "Object.h"
#include "Car.h"
//#include "Lorry.h"
//#include "Vector.h"
using namespace std;
 
int main(int argc, char *argv[])
{
    Car *a=new Car;//создаем объект класса Car
    a->Input();
//  Lorry *b=new Lorry; //создаем объект класса Lorry
//  b->Input();
    /*Vector v(10);//Создаем вектор
    Object*p=a;//ставим указатель на объект класса Car
    v.Add(p);//добавляем объект в вектор
    p=b;//ставим указатель на объект класса Lorry
    v.Add(p); //добавляем объект в вектор
    v.Show();//вывод вектора
    v.Del();//удаление элемента
    cout<< "nVector size="<<v();
    */
    system("PAUSE");
    return EXIT_SUCCESS;
}
C++
1
2
3
4
5
6
7
8
9
using namespace std;
class Object
{
public:
Object(void);
virtual void Show()=0;
virtual void Input()=0;
virtual ~Object(void);
};
C++
1
2
3
4
5
6
7
#include "Object.h"
Object::Object(void)
{
}
Object::~Object(void)
{
};

Car.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>
using namespace std;
class Car:
 public Object
{
 public:
        Car(void);//конструктор без параметров
 public:
        virtual ~Car(void);//деструктор
        void Show();//функция для просмотра атрибутов класса с помощью указателя
        void Input();//функция для ввода значений атрибутов
        Car(string,int,int);//конструктор с параметрами
        Car(const Car&);//конструктор копирования
        //селекторы
        string Get_mark(){return mark;}
        int Get_cyl(){return cyl;}
        int Get_power(){return power;}
        //модификаторы
        void Set_mark(string);
        void Set_cyl(int);
        void Set_power(int);
        Car&operator=(const Car&);//перегрузка операции присваивания
        protected:
                  string mark;
                  int cyl;
                  int power;
 };

car.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
//конструктор без параметров
Car::Car(void)
{
    mark="";
    cyl=0;
    power=0;
}
//деструктор
Car::~Car(void)
{
}
//констрктор с параметрами
Car::Car(string M,int C,int P)
{
    mark=M;
    cyl=C;
    power=P;
}
//конструктор копирования
Car::Car(const Car& car)
{
    mark=car.mark;
    cyl=car.cyl;
    power=car.power;
}
//селекторы
void Car::Set_cyl(int C)
{
    cyl=C;
}
void Car::Set_mark(string M)
{
    mark=M;
}
void Car::Set_power(int P)
{
    power=P;
}
//оператор присваивания
Car&Car::operator=(const Car&c)
{
    if(&c==this)return *this;
        mark=c.mark;
        power=c.power;
        cyl=c.cyl;
    return *this;
}
//метод для просмотра атрибутов
void Car::Show()
{
    cout<<"nMARK : "<<mark;
    cout<<"nCYL : "<<cyl;
    cout<<"nPOWER : "<<power;
    cout<<"n";
}
//метод для ввода значений атрибутов
void Car::Input()
{
    cout<<"nMark:"; cin>>mark;
    cout<<"nPower:";cin>>power;
    cout<<"nCyl:";cin>>cyl;
};



0



Эксперт С++

1623 / 953 / 782

Регистрация: 06.02.2016

Сообщений: 2,449

Записей в блоге: 30

30.11.2016, 11:17

2

Файл Car.h ничего не знает о существовании такого класса как Object



0



0 / 0 / 0

Регистрация: 01.11.2015

Сообщений: 62

30.11.2016, 11:31

 [ТС]

3

Цитата
Сообщение от Peoples
Посмотреть сообщение

Файл Car.h ничего не знает о существовании такого класса как Object

добавлял #include «Object.h» в файл car.cpp
та же самая ошибка



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

30.11.2016, 11:48

4

В car.h добавляй.



0



I know there are a couple of similar questions(circular include) out stackoverflow and other websites. But I still can’t figure it out and no solutions pop out. So I would like to post my specific one.

I have a Event class who has 2 and actually more subclass, which are Arrival and Landing. The compiler(g++) complains:

g++ -c -Wall -g -DDEBUG Event.cpp -o Event.o
In file included from Event.h:15,
                 from Event.cpp:8:
Landing.h:13: error: expected class-name before ‘{’ token
make: *** [Event.o] Error 1

People said that it’s a circular include. The 3 header files(Event.h Arrival.h Landing.h) are as follows:

the Event.h:

#ifndef EVENT_H_
#define EVENT_H_

#include "common.h"
#include "Item.h"
#include "Flight.h"

#include "Landing.h"

class Arrival;

class Event : public Item {
public:
    Event(Flight* flight, int time);
    virtual ~Event();

    virtual void occur() = 0;
    virtual string extraInfo() = 0; // extra info for each concrete event

    // @implement
    int compareTo(Comparable* b);
    void print();

protected:
    /************** this is why I wanna include Landing.h *******************/
    Landing* createNewLanding(Arrival* arrival); // return a Landing obj based on arrival's info

private:
    Flight* flight;
    int time; // when this event occurs

};

#endif /* EVENT_H_ */

Arrival.h:

#ifndef ARRIVAL_H_
#define ARRIVAL_H_

#include "Event.h"

class Arrival: public Event {
public:
    Arrival(Flight* flight, int time);
    virtual ~Arrival();

    void occur();
    string extraInfo();
};

#endif /* ARRIVAL_H_ */

Landing.h

#ifndef LANDING_H_
#define LANDING_H_

#include "Event.h"

class Landing: public Event {/************** g++ complains here ****************/
public:
    static const int PERMISSION_TIME;

    Landing(Flight* flight, int time);
    virtual ~Landing();

    void occur();
    string extraInfo();
};

#endif /* LANDING_H_ */

UPDATE:

I included Landing.h due to Landing’s constructor is called in the Event::createNewLanding method:

Landing* Event::createNewLanding(Arrival* arrival) {
    return new Landing(flight, time + Landing::PERMISSION_TIME);
}

The problem is with the first line of your header file #ifdef _BASE_H_. It should be #ifndef _BASE_H_ (notice the extra ‘n’)

Here is a brief explanation of what is happening:

#ifdef MACRO_NAME
  <line 1>
  <line 2>
  ...
#endif

This code tells the C++ preprocessor to only include the line1, line2, … in the source code if a macro MACRO_NAME has been defined prior to this point (Note: It’s just the definition of the macro which matters, not it’s value. If you want to predicate code inclusion on macro value, you may use #if)

The technique you are trying to use here is called Include Guard, and it safeguards against the duplicate inclusion of code (mostly by #include preprocessor directive). The idea is include source code of a header file only if some macro (say «M») has not been defined yet, and then inside the header file code the first thing you do is define that macro «M» (so that next call to #include samefile will not include its code again). For creating a Include guard you need to use the #ifndef preprocessor directive (which is the exact opposite of #ifdef, in fact, the extra n stands for «NOT»).

Since you incorrectly used #ifdef, the file base.h was never included (as the only place you define the macro _BASE_H_ is after checking that it is already defined!). Thus the compiler does not know about the class base, leading to the error expected class-name before ‘{’ token

  • Forum
  • General C++ Programming
  • Expected class-name before { token

Expected class-name before { token

I’ve encountered another problem whilst trying to compile a fairly large codebase(about 20 classes). I’m getting the following compiler-error:


/path/to/Sphere.h|9|error: expected class-name before ‘{’ token

This is the problematic code:

1
2
3
#include "GeometricObject.h"

class Sphere : public GeometricObject {

Since there are quite a lot of files, I’m not expecting there to be a straight forward solution to this, but how would I go about finding a solution to this? If someone could point me in the right direction, I would be very grateful;)

It looks like the compiler does not know what GeometricObject is. Find the definition (grep) and verify that it (and its header) is spelled correctly, available in Sphere’s namespace, and public.

I think all that should be covered, but if you would care to take a look, here’s the GeometricObject class

GeometricObject.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#ifndef __GEOMETRICOBJECT__
#define __GEOMETRICOBJECT__

class RGBColor;
class ShadeRec;

#include "Ray.h"
#include "ShadeRec.h"
#include "RGBColor.h"

class GeometricObject {
	public:
		GeometricObject(void);
        	GeometricObject(const GeometricObject& g);
		virtual ~GeometricObject(void);

		virtual bool hit(const Ray& ray, double& tmin, ShadeRec& sr) const = 0;
	protected:
		RGBColor color;	//to be replaced

        GeometricObject& operator =(const GeometricObject& rhs);
};

#endif 

GeometricObject.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include "GeometricObject.h"

GeometricObject::GeometricObject(void) : color(0.0, 0.0, 0.0) {
}

GeometricObject::GeometricObject(const GeometricObject& g) {
}

GeometricObject::~GeometricObject(void) {
}

GeometricObject& GeometricObject::operator =(const GeometricObject& rhs) {
        if (this == &rhs) {
            return (*this);
        }
        color = rhs.color;
        return (*this);
}

1
2
3
4
5
6
#ifndef __GEOMETRICOBJECT__
#define __GEOMETRICOBJECT__

...

#endif 

You might want to check to make sure you have not defined __GEOMETRICOBJECT__ in another file by accident (copy/paste?) since doing so would skip your definition of GeometricObject. The compiler doesn’t seem to think GeometricObject is a class name. Your declaration of Sphere looks correct, so I would guess that the problem is with the base class.

Ok, I checked that now, and it seems fine, I cant see any definitions of __GEOMETRICOBJECT__ anywhere else. I realize now that I forgot to include the full compiler error, maybe that could help:


In file included from World.h:11:0,
                 from ShadeRec.h:9,
                 from GeometricObject.h:9,
                 from GeometricObject.cpp:2:
Sphere.h:9:39: error: expected class-name before ‘{’ token

Ok, here is what happens:
* GeometricObject.cpp includes GeometricObject.h in order to get the definition for class GeometricObject
* GeometricObject.h includes ShadeRec.h in order to get the definition of ShadeRec. Notice that at this point GeometricObject is not defined yet.
* some other include stuff along the chain
* Sphere.h tries to include GeometricObject.h, but the guarding token

__GEOMETRICOBJECT__

has been already defined and nothing happens
* class Sphere tries to derive from Geometric object, but it still has no definition. It will later, after the preprocessor returns from the ShadeRec.h include inside GeometricObject.h, but this is no use at this point

What can you do?
You can use forward declaration as you have used already in some places. Such declaration tells the compiler that you know a certain class is defined somewhere, but you disclose nothing yet about its interface and members.

You can not do this:

1
2
3
4
5
6
// remove #include "GeometricObject.h"

class GeometricObject; // the fore-mentioned forward declaration

class Sphere : public GeometricObject {
...

, because this is inheritance, and the forward declaration provides no information on the size of the GeometricObject class, nor on the interface.

But you can do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef __GEOMETRICOBJECT__
#define __GEOMETRICOBJECT__

class RGBColor;
class ShadeRec; // you already have forward declaration

#include "Ray.h"
// optionally remove #include "ShadeRec.h"
#include "RGBColor.h"

class GeometricObject {
	public:
		GeometricObject(void);
        	GeometricObject(const GeometricObject& g);
		virtual ~GeometricObject(void);

		virtual bool hit(const Ray& ray, double& tmin, ShadeRec& sr) const = 0;
	protected:
		RGBColor color;	//to be replaced

        GeometricObject& operator =(const GeometricObject& rhs);
};

#endif 

, because GeometricObject only refers to ShadeRec, it does not contain ShadeRec objects as member variables and doesn’t inherit from the ShadeRec class.

It is impossible to have mutual containment, like A contains/derives from B, and B contains/derives from A. This would create infinite recursion between the definitions of those two classes.

Regards

You, my good Sir, are a genius! That solves the issue! Thanks so much for taking the time:)

Actually, I made a mistake :) I wrote that you should optionally remove

#include «ShadeRec.h»

. You should definitely remove it. Nonetheless, I’m glad you worked it out.

Regards

Topic archived. No new replies allowed.

Viktor10

0 / 0 / 0

Регистрация: 01.11.2015

Сообщений: 62

1

30.11.2016, 09:17. Показов 11731. Ответов 3

Метки нет (Все метки)


Помогите пожалуйста, при запуске программы выходят такие ошибки
Ошибки:

3 C:prog8_vers2Car.cpp In file included from Car.cpp
5 C:prog8_vers2Car.h expected class-name before ‘{‘ token
C:prog8_vers2Makefile.win [Build Error] [Car.o] Error 1

main

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <cstdlib>
#include <iostream>
#include "Object.h"
#include "Car.h"
//#include "Lorry.h"
//#include "Vector.h"
using namespace std;
 
int main(int argc, char *argv[])
{
    Car *a=new Car;//создаем объект класса Car
    a->Input();
//  Lorry *b=new Lorry; //создаем объект класса Lorry
//  b->Input();
    /*Vector v(10);//Создаем вектор
    Object*p=a;//ставим указатель на объект класса Car
    v.Add(p);//добавляем объект в вектор
    p=b;//ставим указатель на объект класса Lorry
    v.Add(p); //добавляем объект в вектор
    v.Show();//вывод вектора
    v.Del();//удаление элемента
    cout<< "nVector size="<<v();
    */
    system("PAUSE");
    return EXIT_SUCCESS;
}
C++
1
2
3
4
5
6
7
8
9
using namespace std;
class Object
{
public:
Object(void);
virtual void Show()=0;
virtual void Input()=0;
virtual ~Object(void);
};
C++
1
2
3
4
5
6
7
#include "Object.h"
Object::Object(void)
{
}
Object::~Object(void)
{
};

Car.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>
using namespace std;
class Car:
 public Object
{
 public:
        Car(void);//конструктор без параметров
 public:
        virtual ~Car(void);//деструктор
        void Show();//функция для просмотра атрибутов класса с помощью указателя
        void Input();//функция для ввода значений атрибутов
        Car(string,int,int);//конструктор с параметрами
        Car(const Car&);//конструктор копирования
        //селекторы
        string Get_mark(){return mark;}
        int Get_cyl(){return cyl;}
        int Get_power(){return power;}
        //модификаторы
        void Set_mark(string);
        void Set_cyl(int);
        void Set_power(int);
        Car&operator=(const Car&);//перегрузка операции присваивания
        protected:
                  string mark;
                  int cyl;
                  int power;
 };

car.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
//конструктор без параметров
Car::Car(void)
{
    mark="";
    cyl=0;
    power=0;
}
//деструктор
Car::~Car(void)
{
}
//констрктор с параметрами
Car::Car(string M,int C,int P)
{
    mark=M;
    cyl=C;
    power=P;
}
//конструктор копирования
Car::Car(const Car& car)
{
    mark=car.mark;
    cyl=car.cyl;
    power=car.power;
}
//селекторы
void Car::Set_cyl(int C)
{
    cyl=C;
}
void Car::Set_mark(string M)
{
    mark=M;
}
void Car::Set_power(int P)
{
    power=P;
}
//оператор присваивания
Car&Car::operator=(const Car&c)
{
    if(&c==this)return *this;
        mark=c.mark;
        power=c.power;
        cyl=c.cyl;
    return *this;
}
//метод для просмотра атрибутов
void Car::Show()
{
    cout<<"nMARK : "<<mark;
    cout<<"nCYL : "<<cyl;
    cout<<"nPOWER : "<<power;
    cout<<"n";
}
//метод для ввода значений атрибутов
void Car::Input()
{
    cout<<"nMark:"; cin>>mark;
    cout<<"nPower:";cin>>power;
    cout<<"nCyl:";cin>>cyl;
};

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Эксперт С++

1623 / 953 / 782

Регистрация: 06.02.2016

Сообщений: 2,449

Записей в блоге: 30

30.11.2016, 11:17

2

Файл Car.h ничего не знает о существовании такого класса как Object

0

0 / 0 / 0

Регистрация: 01.11.2015

Сообщений: 62

30.11.2016, 11:31

 [ТС]

3

Цитата
Сообщение от Peoples
Посмотреть сообщение

Файл Car.h ничего не знает о существовании такого класса как Object

добавлял #include «Object.h» в файл car.cpp
та же самая ошибка

0

7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

30.11.2016, 11:48

4

В car.h добавляй.

0

The error of C + + compiler is as follows:

error: expected class-name before ‘{’ token

When deriving a class, you need to confirm whether it contains the header file of the base class.

If the header file of the base class is included, an error is still reported. As mentioned above, check the header file contained in the base class header file.
For example, all the information about an error is as follows:

aarch64-himix100-linux-g++ -c ./src/base.cpp ./src/host.cpp ./src/main_test.cpp ./src/mcu.cpp ./src/uart1.cpp 
In file included from ./src/../include/main_test.h:6:0,
                 from ./src/../include/base.h:6,
                 from ./src/base.cpp:1:
./src/../include/uart1.h:10:1: error: expected class-name before ‘{’ token
 {
 ^
make: *** [main_test.o] Error 1

There are base classes in the base. H file. Uart1. H is the class to be derived. But look at all the above error information, it appears from the sixth line of base. H. Find line 6, which is the header file of the main function (test program).
Put the header file in line 6 base.cpp It’s OK.

In fact, the above situation should not appear in base. H and base.cpp The header file of the test file should not appear in.

Put the header files (such as # include & lt; pthread. H & gt;) in the corresponding header files (such as base. H).

When testing, you only need to include the base. H file to test the functions in the base.

Read More:

Ошибка этого вида обычно возникает при попытке использовать тип данных, который еще не определен.

Пример. Есть основной класс mother и подкласс daughter:

//main.cpp
#include "mother.h"
#include "daughter.h"
#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    mother mom;
    mom.saywhat();
    return 0;
}
//mother.h
#ifndef MOTHER_H
#define MOTHER_H

class mother
{
public:
    mother();
    void saywhat();
};

#endif // MOTHER_H
//mother.cpp
#include "mother.h"
#include <iostream>

using namespace std;

mother::mother()
{
}

void mother::saywhat()
{
    cout << "WHAAAAAAT" << endl;
}
//daughter.h
#ifndef DAUGHTER_H
#define DAUGHTER_H

class daughter: public mother
{
public:
    daughter();
};

#endif // DAUGHTER_H
//daughter.cpp
#include "daughter.h"
#include "mother.h"
#include <iostream>

using namespace std;

daughter::daughter()
{
}

Компилятор выдает следующую ошибку:

daughter.h  5  error: expected class-name before ‘{’ token

Проблема в том, что при создании класса daughter базовый класс mother еще не определен. Исправляется это добавлением в daughter.h строки

//daughter.h
#ifndef DAUGHTER_H
#define DAUGHTER_H

#include "mother.h" // добавленная строка

class daughter: public mother
{
public:
    daughter();
};

#endif // DAUGHTER_H

As the same for the C — Error / Warning section, I made this one to summarize common mistakes when I tried to compile my code.

So let’s go to see some good errors and warnings in C++ (I’m sure it is also a great moment for you when you discovered these errors).

1. Main.cpp:(.text+0x1f): undefined reference to `Parent::Parent()’

A. The problem

A very common error!
Did you include the parent.cpp file in your Makefile?
Did you compile with this parent.cpp?

B. The solution

Add the correct name of the file into the Makefile to compile it with others .cpp files.

SRC= main.cpp parent.cpp

A. The problem

You forgot to include the two headers of the two parent classes needed.

class Child: public Mother, public Father {
public:
    Child();
    ~Child();
};

B. The solution

Include the right files:

#include "father.hh"
#include "mother.hh"

class Child: public Mother, public Father {
public:
    Child();
    ~Child();
};

3. Virtual base ‘Parent’ inaccessible in ‘Child’ due to ambiguity

A. The problem

You have a Child class that inherits from a Mother and a Father class.
These two parents inherit from the Parent class.
But only one of them inherits with the virtual keyword.

// parent.hh
class Parent {
public:
    Parent();
    virtual ~Parent();
};
// mother.hh
#include "parent.hh"

class Mother: virtual public Parent {
public:
    Mother();
    virtual ~Mother();
};
// father.hh
#include "parent.hh"

class Father: public Parent {
public:
    Father();
    virtual ~Father();
};
//child.hh
#include "father.hh"
#include "mother.hh"

class Child: public Mother, public Father {
public:
    Child();
    virtual ~Child();
};

B. The solution

Add the virual keyword before the public parent call.

// father.hh

#include "parent.hh"

class Father: virtual public Parent {
public:
    Father();
    virtual ~Father();
};

4. ‘Parent’ is an ambiguous base of ‘Child’

A. The problem

You have a Child class that inherits from a Mother and a Father class.
These two parents inherit from the Parent class.
But neither the Mother nor the Father inherits from the Parent with the virtual keyword.

This is the diamond problem because we have a Child that inherits from two classes (Mother and Father) that both inherit from a Parent.
The compiler doesn’t know which class called because without the virtual keyword, it creates the class Parent twice.
And we have then two inheritance trees.

// parent.hh
class Parent {
public:
    Parent();
    virtual ~Parent();
};
// mother.hh
#include "parent.hh"

class Mother: public Parent {
public:
    Mother();
    virtual ~Mother();
};
// father.hh
#include "parent.hh"

class Father: public Parent {
public:
    Father();
    virtual ~Father();
};
//child.hh
#include "father.hh"
#include "mother.hh"

class Child: public Mother, public Father {
public:
    Child();
    virtual ~Child();
};

B. The solution

Add the virual keyword before the public parent call.
The compiler will now creates only one instance of the Parent class, and links the both children (Father and Mother) to the same memory area of the unique Parent.

// father.hh

#include "parent.hh"

class Father: virtual public Parent {
public:
    Father();
    virtual ~Father();
};
// mother.hh
#include "parent.hh"

class Mother: virtual public Parent {
public:
    Mother();
    virtual ~Mother();
};

5.  Constructor.cpp:(.text+0x14): undefined reference to `vtable for Constructor’

A. The problem

This problem may be different things.

For example it may missing something. The Constructor is there but the Destructor isn’t.

B. The solution

Implementing the Destructor.

6. error: variable ‘std::ifstream ifile’ has initializer but incomplete type

A. The problem

You forgot to include <fstream>. 

B. The solution

Include it:

#include <fstream>

7. error: expected primary-expression before ‘<<’ token

A. The problem

You certainly use a semicolon before the end of the function. 

Exemple:

std::cout << typeInt->getType(); << std::endl;

B. The solution

Remove it:

std::cout << typeInt->getType() << std::endl;

8. error: lvalue required as left operand of assignment

A. The problem

The asterisk (*) is not put at the right place. 

Exemple:

You are using an iterator i and you want to put the 8 value inside the value before the current iterator.
So you try to do:

(*i - 1) = 8;

B. The solution

Change the place if the asterisk before the right parenthesis.

*(i - 1) = 8;

9. error: looser throw specifier for ‘virtual MyClass::~MyClass()’
error:   overriding ‘virtual MyException::~MyException() throw ()’

A. The problem

In the derived class from std::exception, we have the following destructor:

virtual ~MyException() throw();

B. The solution

Add the same prototype destructor to your derived class from MyException.

virtual ~MyClass() throw();

This topic has been deleted. Only users with topic management privileges can see it.

  • Hey,
    I have built this class:

    #ifndef FUNCTIONNODE_H
    #define FUNCTIONNODE_H
    
    #include "node.h"
    
    class FunctionNode : public Node
    {}; //error here
    #endif // FUNCTIONNODE_H
    

    And get this error:

    error: expected class-name before '{' token
     {
     ^
    

    And I don’t know why. The class name is there, so the mistake is different to the error I think, but I got no other errors.
    Any ideas?
    Thanks for answers


  • are you sure it knows Node ?
    and its not node or anything like that ?


  • I added

    class Node;
    

    and now I get this:

     error: invalid use of incomplete type 'class Node'
     class FunctionNode : public Node
                                 ^
    

    Looks like you are right, it didn’t know class Node but I unfortunately don’t know what this really means… why is it incomplete type? Class Node is a QGraphicsItem derived class.


  • Hi

    this compiles fine here
    class TestNode{};
    class TestNodeChild : TestNode {
    };

    Incomplete means «Hey you only told me the class name»
    Nothing more.
    And that is not so good with inheritance as it needs to know base class ctor etc.

    When you do
    class node;
    That is a forward. And tells only name.
    It speed up compilation when allowed.
    The cure is full include
    #include «node.h»


  • @mrjj
    Ok… This is weird because I did include node.h . What does it need more?
    It has the class name and the header file. Is there a problem, that Node derives from QGraphicsItem or sth?


  • Hi,

    Can you also post the content of node.h


  • @Niagarer said in expected class-name error:

    Is there a problem, that Node derives from QGraphicsItem or sth?

    Nope.
    Unless the .h have some error that prevents parsing, then it should be fine.

    But as mr sgaist says, please show whole file so we can see if we spot it.

    I assume its not just because in .h file node and you use Node. (big vs small letters)


  • SOLUTION
    Yes, the problem was a bit bigger.

    Summarized:
    It was a problem with including other classes in the header files of the classes. The solution is, to use forward declaration ( class myClass; ) and include the myclass.h in the source (.cpp) file, not in the header file. I did not do this consequent and so, my derived class knew the parent class but thought, it would not have any content. Why, is good explained here (look to the answer post by Ben Voigt):
    https://stackoverflow.com/questions/5319906/error-expected-class-name-before-token

    Thanks for your help!!



  • Recommended Answers

    I have a few other subclasses of Event and they aren’t giving me any trouble.

    How are their class declarations different from this one? I don’t see anything in this one that’s incorrect.

    Jump to Post

    you need {} in class train;

    so it needs to be

    class Train{};

    No, that’s a forward declaration. You don’t need the braces. If you are going to use another class as an object in this class, that class must be defined first. However you don’t need the full declaration …

    Jump to Post

    I would like to see Event.h

    Can you please upload the same?

    Also, posting in bits and pieces of code is most irritating.

    You are posting it because you don’t know what the error is. Then how do you expect yourself to understand what part of code …

    Jump to Post

    All 9 Replies

    Member Avatar

    jonsca

    1,059



    Quantitative Phrenologist



    Team Colleague



    Featured Poster

    12 Years Ago

    I have a few other subclasses of Event and they aren’t giving me any trouble.

    How are their class declarations different from this one? I don’t see anything in this one that’s incorrect.

    Member Avatar

    12 Years Ago

    you need {} in class train;

    so it needs to be

    class Train{};

    Also can you explain this bit here?

    Arrival(int time, Train* newTrain);

    Edited

    12 Years Ago
    by Anarionist because:

    n/a

    Member Avatar

    jonsca

    1,059



    Quantitative Phrenologist



    Team Colleague



    Featured Poster

    12 Years Ago

    you need {} in class train;

    so it needs to be

    class Train{};

    No, that’s a forward declaration. You don’t need the braces. If you are going to use another class as an object in this class, that class must be defined first. However you don’t need the full declaration you can «forward declare» it just so that the compiler knows it exists.

    Also can you explain this bit here?

    Arrival(int time, Train* newTrain);

    This is a constructor for Arrival which takes two arguments, an integer and a pointer to an object of type Train (hence the forward declare before).

    I don’t know if this has anything to do with the problem at hand but when you define a constructor aside from the default one you have to explicitly define the default one. So you’d need: Arrival() {} amongst your public declarations (or you can implement something if you need a default behavior).

    Edited

    12 Years Ago
    by jonsca because:

    n/a

    Member Avatar

    12 Years Ago

    I would like to see Event.h

    Can you please upload the same?

    Also, posting in bits and pieces of code is most irritating.

    You are posting it because you don’t know what the error is. Then how do you expect yourself to understand what part of code is causing the problem. Just because the compiler is pointing to one line doesn’t make that line the culprit.

    Member Avatar

    jonsca

    1,059



    Quantitative Phrenologist



    Team Colleague



    Featured Poster

    12 Years Ago

    I’m curious if it is the Event.h, why are some of the derived classes working and not others?

    @OP: have you actually been able to employ the other derived classes in (working) code or was that just speculation?

    I concur with Thomas, it couldn’t at all hurt for us to have more of your code to test.

    Member Avatar

    12 Years Ago

    Arrival.h:7: error: expected class-name before ‘{’ token

    #ifndef ARRIVAL_H
    #define ARRIVAL_H

    #include "Event.h"

    using namespace std;

    Most likely you are not including anything from the std namespace via the Event .h, so the namespace std remains unknown to the compiler and cannot be used there. I.e. perhaps remove the using namespace std; altogether, (if there will be no use for it in that header file). Otherwise, #include the necessary headers and you’ll be able to keep the rest of this header file as is.

    Edited

    10 Years Ago
    by mike_2000_17 because:

    Fixed formatting

    Member Avatar

    12 Years Ago

    Event.h

    #ifndef EVENT_H
    
    #define EVENT_H
    #include "NodeItem.h"
    #include "Train.h"
    using namespace std;
    
    class Train;
    class Event : public NodeItem {
    
    	protected:
    	int time;
    	Train * train;
    
    	public:
    	virtual ~Event(); 
    	int compareTo(NodeItem* item);
    	virtual void print()=0;
    	virtual void activate()=0;
    	void setTime(int time); 
    	int getTime();
    	void setTrain(Train* train);
    	Train* getTrain();
    
    };
    #endif

    for reference Departure.h which isn’t giving me trouble
    Note: this one doesn’t mind that it don’t forward declare Train, I figure this means it’s getting Event.h forward declare of it, or I was wrong in my previous statement saying they’re not giving me trouble, I haven’t tested them individualy yet.

    #ifndef DEPARTURE_H
    
    #define DEPARTURE_H
    #include "Event.h"
    using namespace std;
    
    class Departure : public Event{
    public:
    	Departure(int time, Train * newTrain);
    	void print();
    	void activate();
    	~Departure(); 
    };
    #endif

    I’ll test my code seperatly without Arrival to see what it says in a bit, thank you for the responses so far.

    things to try:
    Try without Arrival (to test others)
    Try without Namespace Std
    Make a NULL constructor

    Member Avatar

    jonsca

    1,059



    Quantitative Phrenologist



    Team Colleague



    Featured Poster

    12 Years Ago

    Note: this one doesn’t mind that it don’t forward declare Train, I figure this means it’s getting Event.h forward declare of it, or I was wrong in my previous statement saying they’re not giving me trouble, I haven’t tested them individualy yet.

    Arrival shouldn’t need it then either then as it’s part of Event.h. It’s possible that’s goofing you up too. Well, try all the suggestions and see what happens.

    Member Avatar

    12 Years Ago

    Alright I ended up completely rewriting Arrival.cpp and Arrival.h even though I couldn’t distinguish what was wrong with them, and now I’ve managed to make it work and now face new errors (which I’ll post in another thread when I exhaust my options)


    Reply to this topic

    Be a part of the DaniWeb community

    We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
    and technology enthusiasts meeting, networking, learning, and sharing knowledge.

  • Ошибка exiting pxe rom при загрузке windows
  • Ошибка existing state of has been invalidated
  • Ошибка exim rejected rcpt
  • Ошибка exe не является приложением win32 что делать
  • Ошибка exe err not found configure mp csv