无法"this"指针传递到另一个类并在 CPP 中调用该类的任何方法

Unable to pass "this" pointer to another class and calling any methods of that class in CPP

本文关键字:调用 CPP 方法 任何 指针 无法 另一个 this      更新时间:2023-10-16

在这里,我尝试使用"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?需要做这样的事情通常表明你应该重组你的代码。有多种方法可以解决这些问题,每种方法都有其优点和缺点。但这是在代码审查中要问的问题。