无法将“ this”指针传递给另一个类并在CPP中调用该类的任何方法

问题描述 投票:0回答:1

[这里,我试图使用“ 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) {

    }
};
c++ oop pointers interface
1个回答
0
投票

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();
} 

还有更好的方法吗?需要执行类似操作通常表明您应该重组代码。但这是在codereview上提出的问题。

© www.soinside.com 2019 - 2024. All rights reserved.