因此,出于某种原因,当我尝试编译时,我在 main.cpp 中收到一个错误:value 和 balance 未在范围内声明。
我在 main 中使用了 #include "account.h"那么为什么它们没有定义呢?
您还看到我的类有任何问题吗,包括构造函数和析构函数。
账户.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;
}
主要.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();
};
如果代码风格不好,我很抱歉,我在堆栈溢出编辑器上遇到了困难。
最佳答案
您指的是 value
和 balance
就好像它们是普通变量一样,但它们不是 - 它们是实例变量。你应该有一个对象来引用它们:
account c;
cout << "withdrawing " << c.value << endl;
如果您从方法内部访问它们 - 例如,从 account::deposit
- 那么 value
是 this->value< 的语法糖
,所以你可以这样使用它;该对象实际上是 *this
。这些语句是等价的:
balance += value;
balance += this->value;
balance += (*this).value;
关于c++ - 类 header.h 不包含在 main 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727297/