Почему этот typedef не работает

#c #typedef

#c #typedef

Вопрос:

Этот код работает, если в 7-й строке вниз написано «typedef char ItemType», но вместо этого я сделал его typedef для объекта EventInfo. Компилятор MSVS говорит некоторые действительно странные вещи…

error C2146: syntax error : missing ';' before identifier 'ItemType'
error C4430: missing type specifier - int assumed. Note: C does not support default-int

Но я не понимаю, почему он работает правильно, когда это a char .

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

 #include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

const int MaxQueueSize = 8; // Queue Struct can hold up to 8
typedef EventInfo ItemType; // the queue's data type !DOES NOT COMPILE

enum EventType {Arrival, Depart};
class EventInfo
{
public:
    EventInfo() : eTime(0), aTime(0), minutes(0) {}
    int eventTime();
    int duration();
    void ScheduleEvent(int eTime, int duration);
    bool compare(int eTime);
private:
    int eTime; //either the arrival time of the next customer or the departure time of the customer currently at the teller window
    int aTime; //either the service time for the arriving customer or the wait time for the customer at the teller window
    float minutes;
};
int EventInfo::eventTime()
{
    return this->eTime;
}
int EventInfo::duration()
{
    return this->aTime;
}
void EventInfo::ScheduleEvent(int eTime, int duration)
{
    this->eTime = eTime;
    this->aTime = duration;
}
bool EventInfo::compare(int eTime)
{
    return (eTime == this->eTime);
}

///////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////
////////////////

class CPPQueue
{
public:
    CPPQueue() : front(0), rear(0), count(0) { };
    ItemType item[MaxQueueSize];
    bool IsEmpty() const;
    bool IsFull() const;
    void Enqueue(ItemType newItem);
    void PrintQ();
    void PrintQueueInfo();
    ItemType Dequeue();
    int Count();
private:
    int front, rear;
    int count;
};
bool CPPQueue::IsEmpty() const 
{
    return (this->count == 0);
}
bool CPPQueue::IsFull() const 
{
    return (this->count == MaxQueueSize);
}
void CPPQueue::Enqueue(ItemType newItem)
{
    if(this->count == MaxQueueSize)
    {
        cerr << "Error! Queue is full, cannot enqueue item.n" << endl;
        exit(1);
    }
    this->item[this->rear] = newItem;
    this->rear  ;
    if (this->rear == MaxQueueSize)
    {
        this->rear = 0; // adjustment for circular queue
    }
    this->count  ;
}
ItemType CPPQueue::Dequeue()
{
    ItemType theItem;
    if(this->count == 0)
    {
        cerr << "Error! Queue is empty, cannot dequeue item.n" << endl;
        exit(1);
    }
    theItem = this->item[this->front ];
    this->front  ;
    if (this->front == MaxQueueSize)
    {
        this->front = 0; // adjustment for circular queue
    }
    this->count--;
    return theItem;
}
// Function PrintQ() prints the contents of the queue without changing
// the queue. Printing starts at the "front" index and stops before we
// get to the "rear" index. A decrementing counter controls the loop.
//
void CPPQueue::PrintQ()
{
    int i;
    int qindex = this->front;
    for(i = this->count; i > 0; i--)
    {
        cout << this->item[qindex] ;
        qindex = (  qindex) % MaxQueueSize; // adjustment for circular queue
        if(i > 1)
            cout << ", ";
    }
}
// Helper function for the main program below.
void CPPQueue::PrintQueueInfo()
{
    cout << "The queue contains: ";
    PrintQ();
    cout << endl;
}
int CPPQueue::Count()
{   
    return this->count;
}


enum TellerStatus {Idle, Busy};
class Teller
{
public:
    Teller() : status(Idle), idleTime(0), totalIdleTime(0) {}
    void changeStatus(TellerStatus status);
    TellerStatus getStatus(void);
private:
    TellerStatus status;
    int idleTime; //!
    int totalIdleTime; //!!
};
void Teller::changeStatus(TellerStatus status)
{
    this->status = status;
}
TellerStatus Teller::getStatus()
{
    return this->status;
}

class Bank
{
public:
    Bank() : Clock(0.0) {}
    void RunSimulation();
private:
    EventInfo Event[2]; // array of two events - next arrival and next departure
    CPPQueue WaitLine; // the customer wait line [with max size = 8]
    float Clock; // to keep track of Current Bank Time
    Teller theTeller; // the single teller in the bank
    ifstream myfile;
    void ProcessArrival(), ProcessDeparture(), PrintHeader(), PrintReportLine(), PrintStatsReport();
};
void Bank::RunSimulation()
{

}
void Bank::ProcessArrival()
{
    int a, b;
    string filename, x;
    filename = "P3Data1.txt";
    myfile.open(filename);
    while (myfile >> a >> b)
    {
        Event[1].ScheduleEvent(a, b);
        WaitLine.Enqueue(Event);
    }
}

int main()
{
    Bank myBank;
    myBank.RunSimulation();

}
 

Ответ №1:

Имя EventInfo можно использовать только с момента его объявления. Ваш typedef слишком ранний, и компилятор еще не знает, что такое a EventInfo .

Вы можете переместить typedef ниже определения класса или указать компилятору, что EventInfo это класс:

 typedef class EventInfo ItemType;
 

Ответ №2:

В C , в отличие от Java, вы можете использовать только имена, которые были объявлены ранее в файле. Так что просто измените порядок:

 class EventInfo { /* ... */ };
typedef EventInfo ItemType;
 

На самом деле, достаточно просто объявить класс, если вы пока не хотите его определять: class EventInfo;

Ответ №3:

Поместите typedef после определения класса. Вы не можете выполнить typedef для неизвестных типов.

Ответ №4:

Сначала вам нужно переслать объявление class EventInfo;

В противном случае ваш typedef понятия не имеет, что такое EventInfo.

Тогда у вас возникают различные проблемы, например, вам нужно перегрузить << для класса EventInfo и т. Д.