c++ - 无法将“this”指针传递给另一个类并在 CPP 中调用该类的任何方法
问题描述
在这里,我尝试使用“this”关键字将 ATMMachine 的实例传递给 HasCard 类,并尝试使用该实例从 HasClass 调用 ATMMachine 的任何方法。但我无法调用 ATMMachine 的任何方法。例如无法打电话machine->insertCard();
有人可以帮我找出问题所在吗?CPP中有没有更好的方法在类之间进行通信?
class ATMState{
virtual void insertCard() = 0;
virtual void ejectCard() = 0;
virtual void insertPin(int pinNumber) = 0;
virtual void withdrawCash(int amount) = 0;
};
class ATMMachine;
class HasCard: public ATMState {
private:
ATMMachine* machine;
public:
HasCard(ATMMachine* _machine) {
machine = _machine;
machine->insertCard();
}
void insertCard() {
}
void ejectCard() {
}
void insertPin(int pinNumber) {
}
void withdrawCash(int amount) {
}
};
class ATMMachine{
public:
int balance;
ATMState* currentState;
ATMState* hasCard;
ATMState* noCard;
ATMState* hasPin;
ATMState* noCash;
ATMMachine() {
hasCard = new HasCard(this);
// noCard = new NoCard();
// noCash = new NoCash();
// hasPin = new HasPin();
currentState = hasCard;
}
void insertCard() {
cout<<"Card has been inserted" <<endl;
}
void ejectCard() {
}
void insertPin(int pinNumber) {
}
void withdrawCash(int amount) {
}
};
解决方案
But I am not able to call any of the methods of ATMMachine.
使用前向声明class ATMMachine;
,您只能告诉该类存在,但编译器在达到完整的类定义之前不知道其成员函数的任何内容。
这就是为什么你会收到这样的错误:
invalid use of incomplete type 'class ATMMachine' machine->insertCard(); note: forward declaration of 'class ATMMachine' class ATMMachine;
如果您有这种交叉依赖关系,您需要拆分成员函数、构造函数或析构函数的声明及其定义。
class ATMState {
virtual void insertCard() = 0;
virtual void ejectCard() = 0;
virtual void insertPin(int pinNumber) = 0;
virtual void withdrawCash(int amount) = 0;
};
class ATMMachine;
class HasCard : public ATMState {
private:
ATMMachine *machine;
public:
// only declare the constructor here
HasCard(ATMMachine *_machine);
void insertCard() {}
void ejectCard() {}
void insertPin(int pinNumber) {}
void withdrawCash(int amount) {}
};
class ATMMachine {
public:
int balance;
ATMState *currentState;
ATMState *hasCard;
ATMState *noCard;
ATMState *hasPin;
ATMState *noCash;
ATMMachine() {
hasCard = new HasCard(this);
// noCard = new NoCard();
// noCash = new NoCash();
// hasPin = new HasPin();
currentState = hasCard;
}
void insertCard() { cout << "Card has been inserted" << endl; }
void ejectCard() {}
void insertPin(int pinNumber) {}
void withdrawCash(int amount) {}
};
// move the definition of the HasCard constructor after the declaration of ATMMachine
HasCard::HasCard(ATMMachine *_machine){
machine = _machine;
machine->insertCard();
}
Is there any better approach in CPP to communicate between classes?
需要做类似的事情通常表明你应该重组你的代码。有多种方法可以解决这些问题,每种方法各有利弊。但这是在 codereview 上要问的问题。
推荐阅读
- java - 访问通过 Java Webstart 加载的 JAR 文件
- ios - 使用图像缓存时展开 [String] 的问题
- excel - SOAP UI 写入数据时 Excel 公式未更新
- azure-cosmosdb - 将 Azure Cosmos DB 移动到其他租户
- javascript - 尝试在发生错误时显示注册错误块
- extract - 从语法中提取标记
- node.js - 服务器实例,开玩笑和“听 EADDRINUSE :::3000”
- python-3.x - 如何创建字典组合?最昂贵的汽车问题
- vim - Neovim:如何设置 guicursor 使光标闪烁?
- ruby-on-rails - 更新另一个模型的属性