0

I posted this in the C++ forum, but decided to repost here as it relates to software development, and this might be a better audience for it.

I'm trying to implement a Visitor Pattern in c++, but I'm having problems with the elements being visited in turn having their children visited. For example I have a class Element, which has a vector of Nodes (can be elements or any classes that inherit from node):

class Element : public Node{
	public:
		Element();
		Element(string n, string v = " ");
		~Element();
		void Accept(Visitor& v);
		vector<Node*> nodeVec;
		vector<Attr*> attrVec;
	private:
		string name, value;
};

void Element::Accept(Visitor& v)
{
	v.VisitElement(*this);
}

And I have a concreteVisitorA class, which inherits from an abstract visitor class

class ConcreteVisitorA : public Visitor {
	public:
		ConcreteVisitorA();
		~ConcreteVisitorA();
		void VisitElement(Element e);
};

void ConcreteVisitorA::VisitElement(Element e)
{
	int numNodes = e.GetNumNodes();
	int numAttrs = e.GetNumAttrs();
	cout << "Visitor has found " << numNodes << " noes\n";
	e.nodeVec[0]->Accept(this);
		
	}

The problem is when it gets to the last line of VisitElement, where the first member of the vector is visited i get the error

concreteVisitorA.cc:20: error: no matching function for call to 'Node::Accept(ConcreteVisitorA* const)'
node.h:9: note: candidates are: virtual void Node::Accept(Visitor&)

The Accept method has to have visitor passed to it by reference, because it is abstract. But "this" is a pointer and the whole thing craps out. Any suggestions?

1
Contributor
1
Reply
2
Views
7 Years
Discussion Span
Last Post by hoolr
0

I simply added another implementation of accept, which could take take a pointer and now it works.

void Element::Accept(Visitor& v)
{
	v.VisitElement(*this);
}
void Element::Accept(Visitor* v)
{
	v->VisitElement(*this);
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.