C++ ~ вызов функции в клиенте дает ошибку: идентификатор ____ не определен

Я обращаюсь к вам с проблемой, в которой задействовано несколько разных файлов. Я не уверен, почему я получаю ошибку, указанную в заголовке. Позвольте мне поместить файлы ниже и идти оттуда.

DummyClient.cpp

#include "Gameboard.h"          //for Gameboard
#include "Location.h"           //for function prototypes
#include "zList.h"              //for Zombies
#include <iostream>             //for input/output stream

using namespace std;

void main()
{
    srand(123456789);

    Gameboard myGB;

    myGB = Gameboard();

    ZombieListClass();

    ZombieRec zombieList[MAX_ZOMBIES];

    PopulateZombies(zombieList[MAX_ZOMBIES]); // this throws the error here of "Error: identifier "PopulateZombies" is undefined"

}

zList.h

#ifndef ZLIST_H
#define ZLIST_H

#include "Location.h"   // for list record
#include "ZombieRec.h"
#include "Gameboard.h"

class ZombieListClass
{

    public:
      ZombieListClass();            //default constructor 

      void PopulateZombies(ZombieRec zombieList[]);

      bool IsInBounds(int row, int col);


    private:
      ZombieRec list[MAX_ZOMBIES];      //stores the items in the list
      int length;                           //# of values currently in the list
      int currPos;                      //position of current element
      int strength;                 // health and attack units of a zombie

};

#endif

zList.cpp

#include "zList.h"

ZombieListClass::ZombieListClass()      //default constructor 
{

    length = 0;
    currPos = 0;
    strength = 5;
    LocationRec zombieLoc;

}

void ZombieListClass::PopulateZombies(ZombieRec zombieList[])
{
    int row, col;

    for (int i = 0; i < MAX_ZOMBIES; i++)
    {
        row = rand() % MAX_ROW + 1;
        col = rand() % MAX_COL + 1;

        while (!IsInBounds(row, col))
        {
            row = rand() % MAX_ROW + 1;
            col = rand() % MAX_COL + 1;
        }

        zombieList[i].currLoc.row = row;
        zombieList[i].currLoc.col = col;

    }


}

bool ZombieListClass::IsInBounds(int row, int col)
{

    if (row == 0 || row == MAX_ROW + 1 || col == 0 || col == MAX_COL + 1)
    {
        return false;
    }
    else
    {
        return true;
    }

}

Игровая доска.h

#ifndef GAMEBOARD_H
#define GAMEBOARD_H


#include "Location.h" 
#include "ZombieRec.h"
#include "zList.h"


const int MAX_ROW = 3;      // total number of rows in the board
const int MAX_COL = 3;      // total number of cols in the board



class Gameboard
{

public:

    Gameboard();


private:
    int boardSizeArr[MAX_ROW + 2][MAX_COL + 2];


}; // end Gameboard

#endif

и, наконец, Gameboard.cpp

#include "Gameboard.h"

Gameboard::Gameboard()
{

    // Declares a board with a boundary along the outside
    boardSizeArr[MAX_ROW + 2][MAX_COL + 2]; 

}

Я не ищу, чтобы меня кормили с ложки, и чтобы кто-то решил мою проблему за меня, я пытаюсь понять, что я делаю неправильно, чтобы оставшаяся часть моего проекта не была такой ухабистой, как это было все это время. .

Оглядываясь назад на свою ошибку, «идентификатор «PopulateZombies» не определен», я не могу представить, почему это так. Может ли это иметь какое-то отношение к тому, как я делаю вещи? Если я не упомянул какой-либо код (я не поместил туда все, но думаю, что у меня есть все необходимое), просто дайте мне знать, я могу общаться взад и вперед столько времени, сколько это займет.

Заранее спасибо всем, кто попытается помочь :)

-Энтони


person SiggyxLeGiiT    schedule 05.10.2014    source источник


Ответы (2)


В общем, вы вызываете функцию, используя переменную, вместо того, чтобы вызывать ее напрямую, если она определена в классе:

ZombieListClass zombieList=new ZombieListClass();  // add a variable here

ZombieRec zombieList[MAX_ZOMBIES];

zombieList.PopulateZombies(zombieList[MAX_ZOMBIES]); // See the difference?
person Hai Bi    schedule 05.10.2014
comment
Вы знаете, сразу после того, как я отправил вопрос, я посмотрел на Gameboard myGB; прямо над ним в файле клиента. Иногда я чувствую себя таким глупым, что не замечаю этого. Благодарю вас! - person SiggyxLeGiiT; 05.10.2014

Я не уверен, является ли ошибка, которую вы опубликовали, единственной ошибкой. Вот что я вижу в вашем main.cpp

#include "Gameboard.h"          //for Gameboard
#include "Location.h"           //for function prototypes
#include "zList.h"              //for Zombies
#include <iostream>             //for input/output stream

using namespace std;

void main()
{
    srand(123456789);

    Gameboard myGB;

    myGB = Gameboard();//The constructor"Gameboard()" is automatically called when you defined 
                       //myGB in the previous line,

    ZombieListClass();//see Hai Bi's great answer on this one

    ZombieRec zombieList[MAX_ZOMBIES];//ZombieRec is a member of ZombieListClass, use . to access it

    PopulateZombies(zombieList[MAX_ZOMBIES]); //Also see  Hai Bi's answer

}

Мой совет — вернуться к концепции конструктора и определения класса, прежде чем приступить к работе с проблема такая.

person No harmer    schedule 05.10.2014