Help with this forward declaration problem-ish

Started by
1 comment, last by Concentrate 14 years, 1 month ago
I trying to learn the visitor pattern. So I am trying to implement a rather simple and stupid example, so no need to point that out. Instead of separating the classes into different file, its rather a small class so I just put everything into one file. Here is the main.cpp :

#include <iostream>
#include "Print.h"

using namespace Print; //template print functions
using namespace std;

class PrintVisitor;
class Char;
class Integer;
class Float;
struct VisitElem;

struct VisitElem {	
	virtual void visit(const PrintVisitor& pv)const = 0;
};

class Char : public VisitElem{
	char ch;
public:
	Char(): ch(0){}
	Char(char c) : ch(c){}
	char elem(){ return ch; }
	void visit(const PrintVisitor& pv)const{ pv.visit(*this); }
};
class Integer{
	int i;
public:
	Integer() : i(0){}
	Integer(int in) : i(in){}
	int elem(){ return i; }
	void visit(const PrintVisitor& pv)const{ pv.visit(*this); }
};
class Float{
	float fl;
public:
	Float() : fl(0.0f){}
	Float(float f) : fl(f){};
	float elem(){ return fl; }
	void visit(const PrintVisitor& pv)const{ pv.visit(*this); }
};
class PrintVisitor{
	void visit(Char ch)const{ print(ch.elem());}
	void visit(Integer i)const{ print(i.elem());}
	void visit(Float fl)const{ print(fl.elem());}
};
int main()
{
	return 0;
}
 

It gives me some errors because of the visit(...) method for each class. Here is the errors :

error C2027: use of undefined type 'PrintVisitor'
error C2228: left of '.visit' must have class/struct/union
I see why the error msg is. Its because the compiler does not know yet that PrintVisitor has a visit method. But I am not sure how to solve this problem. Any help is appreciated.
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
Advertisement
Don't define the functions inline in the class definitions. Define them after class definitions.
Thanks. For some reason I'm mixing java and C++ style. I for about that.
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github

This topic is closed to new replies.

Advertisement