因此由于某种原因,当我尝试编译时,我在main.cpp中得到一个错误:范围内未声明值和余额。

我在main中使用#include“ account.h”,所以为什么未定义它们?

您还看到我的课程有任何问题,包括构造函数和析构函数。

account.cpp

using namespace std;

#include <iostream>
#include "account.h"

account::account(){


}

account::~account(){

}

int account::init(){
cout << "made it" << endl;
  balance = value;

}

int account::deposit(){
  balance = balance + value;
}

int account::withdraw(){
  balance = balance - value;
}


main.cpp

using namespace std;

#include <iostream>
#include "account.h"

//Function for handling I/O
int accounting(){


string command;

cout << "account> ";
cin >> command;
account* c = new account;

    //exits prompt
    if (command == "quit"){
        return 0;
        }

    //prints balance
    else if (command == "init"){
        cin >> value;
        c->init();
        cout << value << endl;
        accounting();
        }

    //prints balance
    else if (command == "balance"){
        account* c = new account;
        cout << " " << balance << endl;
        accounting();
        }

    //deposits value
    else if (command == "deposit"){
        cin >> value;
        c->deposit();
        accounting();
        }

    //withdraws value
    else if (command == "withdraw"){
        cin >> value;
        cout << "withdrawing " << value << endl;
        accounting();
        }

    //error handling
    else{
        cout << "Error! Command not supported" << endl;
        accounting();
        }
}


 int main() {

     accounting();


return 0;
}


帐户

class account{

private:

int balance;

public:

    account();  // destructor
    ~account(); // destructor
    int value;
    int deposit();
    int withdraw();
    int init();

};


抱歉,如果代码风格不好,我在使用堆栈溢出编辑器时会遇到困难。

最佳答案

您引用valuebalance就像它们是普通变量一样,但它们不是-它们是实例变量。您应该有一个引用它们的对象:

account c;
cout << "withdrawing " << c.value << endl;


如果要从方法内部访问它们(例如,从account::deposit访问),则valuethis->value的语法糖,因此可以以这种方式使用它;该对象实际上是*this。这些语句是等效的:

balance += value;
balance += this->value;
balance += (*this).value;

10-06 04:33