【问题标题】:class header.h not included in main类 header.h 不包含在 main 中
【发布时间】:2013-05-24 03:36:01
【问题描述】:

因此,由于某种原因,当我尝试编译时,我在 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;
}

帐户.h

class account{

private:

int balance;

public:

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

};

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

【问题讨论】:

  • 你应该使用包含保护而不是使用new

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


【解决方案1】:

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

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

如果你从一个方法内部访问它们——比如说,从account::deposit——那么valuethis-&gt;value的语法糖,所以你可以这样使用它;该对象实际上是*this。这些语句是等价的:

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

【讨论】:

    【解决方案2】:

    valuebalanceclass account 的成员,它们应该以 c-&gt;valuec-&gt;balance 访问。但是balanceprivate 成员,你不能在main() 中使用它。您需要编写一些访问器函数,例如:

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

    然后将其称为

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

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

    delete c;
    

    【讨论】:

      猜你喜欢
      • 2013-11-11
      • 2011-08-24
      • 2013-11-14
      • 2012-03-27
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 2019-11-03
      相关资源
      最近更新 更多