C ++ method declaration using another class
I am starting to learn C ++ (from Java), so bear with me.
It doesn't seem to me that my method declaration is taking the class I made.
"Context" was not declared
I think I don't understand the fundamental concept, but I don't know what.
Expression.h
#include "Context.h"
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
};
Context.h
#include <stack>
#include <vector>
#include "Expression.h"
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
};
source to share
You need to post your ad Expression
to Context
or vice versa (or both), otherwise you have a circular dependency. For example,
Expression.h:
class Context; // no include, we only have Context*.
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
};
Context.h:
#include <stack>
#include <vector>
class Expression; // No include, we only have Expression*
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
};
You can do forward declarations because you don't need to fully define the classes, because in each case you are only referring to pointers to another class. You will probably need inclusions in the implementation files (i.e. #include "Context.h"
in Expression.cpp
and #include Expression.h
in Context.cpp
).
Finally, don't forget to put include guards in your header files.
source to share
In C ++, class definitions must always end with a semicolon ;
so the example is:
class foo {};
Java and C # do not require this, which is why I see your confusion.
It also looks like both header files include each other. So it's like a snake eating its tail: where does it start? So in your Expression.h, instead of "include" instead of "forward", you can instead:
class Context;
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
}
Last but not least, you must put a compiler guard to prevent the header from being included more than once in the .cpp file. You can put #pragma once
at the top of the header file. This is useful if you are using visual studio and microsoft compiler. I don't know if GCC supports it or not. Or you can wrap your header file like this:
#ifndef EXPRESSION_H_
#define EXPRESSION_H_
class Context;
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
}
#endif
source to share
you may need to forward your Context and Expression class declarations in header files before #include
eg.
#include <stack>
#include <vector>
// forward declaration
class Context;
class Expression;
#include "Expression.h"
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
}
source to share