class header.h不包含在main中

时间:2013-05-24 03:36:01

标签: c++ class constructor implementation header-files

因此,出于某种原因,当我尝试编译时,我得到一个错误,在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;
}

account.h

class account{

private:

int balance;

public:

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

};

对不起,如果代码风格不好,我在堆栈溢出编辑器上遇到了困难。

2 个答案:

答案 0 :(得分:1)

你指的是valuebalance,好像它们是正常变量,但它们不是 - 它们是实例变量。你应该有一个可以引用它们的对象:

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

如果您是从方法内部访问它们 - 例如,从account::deposit - 那么valuethis->value的语法糖,所以您可以这样使用它;该对象实际上是*this。这些陈述是等价的:

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

答案 1 :(得分:0)

valuebalanceclass account的成员,我们可以将其视为c->valuec->balance。但balanceprivate成员,您无法在main()中使用它。你需要写一些访问函数,如:

int account::GetBalance() const
{
    return balance;
}

然后将其称为

cout << " " << c->GetBalance() << endl;

此外,您应该通过调用来释放c的已分配内存。

delete c;