C ++ ERROR: forward declaration 'struct ...?

cyclic switching problem

I am forwarding one of the classes in the header of the other in an attempt to solve their cyclic inclusion. Here are my two files:

First file (Parameter.h):

#pragma once #include "Token.h"` class Expression; class Parameter { public: Parameter() { string = new Token(); identifier = new Token(); expr = new Expression(); } Token* string; Token* identifier; Expression* expr; }; 

Second file (Expression.h):

 #pragma once #include "Token.h" #include "Parameter.h" class Expression { public: Expression() { param1 = new Parameter(); param2 = new Parameter(); op = new Token(); } Expression(Parameter* p1, Token* o, Parameter* p2) { param1 = p1; param2 = p2; op = o; } Parameter* param1; Parameter* param2; Token* op; }; 

As you can see, I forward the Expression expression to Parameter.h, but I still get the following two errors:

forward declaration 'struct Expression'

misuse of the incomplete type 'struct Expression'

I looked through some of the previously asked questions, but still could not solve this problem. Thanks.

+4
source share
3 answers

You cannot redirect an Expression ad because it requires a full ad:

 Parameter() { string = new Token(); identifier = new Token(); expr = new Expression(); // here! } 

What you can do is move the implementation of the Parameter() constructor from the header and into the .cpp file.

+9
source

You need to put the parameter constructor in the cpp file when you call expr = new Expression(); in the constructor, you need to know the specific type of Expression expression.

Parameter.h

 #pragma once #include "Token.h" class Expression; class Parameter { public: Parameter(); Token* token; Token* identifier; Expression* expr; }; 

Parameter.cpp

 #include "Parameter.h" Parameter::Parameter() : token(new Token()), identifier(new Token()), expr(new Expression()) { } 

side of the note: could you use smart pointers instead of raw pointers as a member of the class? also the variable name string can affect std::string .

+4
source

Define the constructor body in a separate cpp file. An advanced class declaration allows you to use pointers or references, rather than the constructor of a direct declared class, because you use the "other" class in the constructor. in ccp file:

 #include "Parameter.h" #include "Expression.h" // ?? Parameter::Parameter(): string (new Token()), identifier(new Token()), expr ( new Expression()) {} Expression::Expression() param1 (new Parameter()), param2 (new Parameter()), op ( new Token()) { } 

(you are now safe if new / constructors drop out)

+2
source

All Articles