获取未定义的类类型错​​误,但我确实创建了类并定义了它

时间:2010-02-12 08:16:00

标签: c++ visual-studio visual-studio-2008 visual-c++

我正在为我的一个课程完成作业。简单地说,我有一个GumballMachine类和一组改变GumballMachine状态的State类。

以下是有问题的代码:

class GumballMachine;

class State {
public:
 virtual void insertQuarter() const = 0;
 virtual void ejectQuarter() const = 0;
 virtual void turnCrank() const = 0;
 virtual void dispense() const = 0; 

protected:
 GumballMachine *GBM;
};

class NoQuarterState : public State {
public: 
 NoQuarterState (GumballMachine *GBM) {
  this->GBM = GBM;  
 }

 void insertQuarter() const {
  cout << "You inserted a quarter\n";  
  **this->GBM->QuarterInserted();** // <--- C2027 error on MSDN  
 }
};

现在在下面我将GumballMachine类定义为:

class GumballMachine {
public:
 GumballMachine(int numOfGB) {
  this->noQuarterState = new NoQuarterState(this);
  this->soldOutState = new SoldOutState(this);
  this->hasQuarterState = new HasQuarterState(this);
  this->soldState = new SoldState(this);
  this->winnerState = new WinnerState(this);
  this->count = numOfGB;
  if (0 < numOfGB) {
   this->state = this->noQuarterState;
  }
  else {
   this->state = this->soldOutState;
  }  
 }

        ... more code ...

 void QuarterInserted() {
  this->state = this->hasQuarterState;
 }

 ... more code ...

protected:
 int count;
 NoQuarterState *noQuarterState;
 SoldOutState *soldOutState;
 HasQuarterState *hasQuarterState;
 SoldState *soldState;
 WinnerState *winnerState;
 State *state;
};

Visual Studios正在抛出C2259和C2027错误,但在查看MSDN之后,我觉得我做得对。也许我只是累了,但我似乎无法找到错误/看我做错了什么。

非常感谢任何帮助。 :d

4 个答案:

答案 0 :(得分:6)

在定义类之前,您无法访问GumballMachine的任何成员,因此您必须将文件拆分为多个文件,每个文件包含一个类,或者在您之后定义NoQuarterState::insertQuarter方法。 GumballMachine类的定义:

class NoQuarterState : public State {
  public: 
    NoQuarterState (GumballMachine *GBM) {
       this->GBM = GBM;  
    }

    void insertQuarter() const; // Declaration only
};

class GumballMachine {
  public:
    ...
};

void NoQuarterState::insertQuarter() const {
  cout << "You inserted a quarter\n";  
  this->GBM->QuarterInserted(); // Works now bec. comp. has seen the def.
}

答案 1 :(得分:1)

GumballMachine类在定义后缺少分号。

答案 2 :(得分:1)

Chris,您需要采用更标准的方法将声明拆分为头文件和定义到模块文件中。

class State需要与State.h类似,NoQuarterState::insertQuarter()的定义之类的内容需要在State.cpp中。

完成后,您将知道哪些.cpp文件需要#include个其他头文件才能进行编译。

class GumballMachine;声明之前你class State是正确的,因为StateNoQuarterState都需要知道名称

答案 3 :(得分:0)

class GumballMachine;宣布上课。如果要取消引用指向该类对象的指针,则必须先定义该类。这通常在头文件中完成。在类定义中必须声明它的所有成员函数和变量,但您可以在任何地方定义这些函数。