【发布时间】:2010-02-12 08:16:00
【问题描述】:
我正在为我的一门课做作业。简单地说,我有一个 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
【问题讨论】:
-
您可能不应该养成将
this->放在所有内容前面的习惯;很混乱。
标签: c++ visual-studio visual-studio-2008 visual-c++