Search code examples
c++syntax-erroridentifier

Visual Studio error C2061: syntax error: identifier


//Species.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Species
{
protected:
    int HP, GroundAttack, AirAttack, MoveMode;
public:
};

// Protoss.h
#pragma once
#include "Species.h"
#include "Terran.h"

class Protoss : public Species
{
protected:
    int PS;
public:
    virtual void Input();
    virtual void Output();
    void B_AbilityAttack_A(Terran *);
};

// Terran.h
#pragma once
#include "Species"
#include "Protoss.h"

class Terran : public Species
{
public:
    virtual void Input();
    virtual void Output();
    void A_AbilityAttack_B(Protoss *);
};

"error C2061: syntax error : identifier 'Terran'"

"error C2061: syntax error : identifier 'Protoss'"

error in: void A_AbilityAttack_B(Protoss *) and void B_AbilityAttack_A(Terran *)

How to fix it?

After fix In a method of class Protoss, I wrote:

void Protoss::B_AbilityAttack_A(Terran *x)
{
    if (this->AbilityAttack() == 0 && x->GetMoveMode() == 0)
    {
        x->SetHP(x->GetHP() - this->GAttack());
    }
    else if (this->AbilityAttack() == 1 && x->GetMoveMode() == 0)
    {
        x->SetHP(x->GetHP() - this->GAttack());
    }
    else
    {
        x->SetHP(x->GetHP() - this->AAttack());
    }
}

And error in x : "pointer to incomplete class type is not allowed"

So how to fix it?


Solution

  • You have a circular dependency. Remove the include of Protoss by Terran and vice versa, the use forward declarations instead.

    // Protoss.h
    #pragma once
    #include "Species.h"
    
    class Terran;
    class Protoss : public Species
    {
    protected:
        int PS;
    public:
        virtual void Input();
        virtual void Output();
        void B_AbilityAttack_A(Terran *);
    };
    
    // Terran.h
    #pragma once
    #include "Species"
    
    class Protoss;
    class Terran : public Species
    {
    public:
        virtual void Input();
        virtual void Output();
        void A_AbilityAttack_B(Protoss *);
    };
    

    This will work because you don't need the full class definitions because the arguments are pointers, you just need to forward declare them.