C++ 语义问题:“'使用未声明的标识符 'balance'”

C++ Semantic issue: "'use of undeclared identifier 'balance'"

我是 C++ 的新手,正在使用 Xcode,但我遇到了问题, 在我的主 .cpp 文件中 Account.cpp 代码是-

#include <iostream>

using namespace std;
#include "Account.h"
Account::Account()

{
    double balance=0;
    balance=0;
}
Account getbalance()
{
    return balance;
}

void deposit(double amount)
{
    balance+=amount;
}
void withdraw(double amount)
{
    balance-=amount;
}
void addInterest(double interestRate)
{
    balance=balance*(1+interestRate);
}

我想我错过了什么,但我不确定在哪里,如果您能提供帮助,我们将不胜感激。

**头文件Account.h是-

#include <iostream>
using namespace std;
class Account
{
private:
    double balance;
public:
    Account();
    Account(double);
    double getBalance();
    void deposit(double amount);

    void withdraw(double amount);
    void addInterest(double interestRate);
};

按如下方式编写构造函数

Account::Account()
{
    balance = 0.0;
}

我假设 balance 是 class 帐户的 double 类型的数据成员。

或者你可以这样写

Account::Account() : balance( 0.0 ) {}

所有这些函数定义如果函数是class成员函数必须至少看起来像

double Account::getBalance()
{
    return balance;
}

void Account::deposit(double amount)
{
    balance+=amount;
}
void Account::withdraw(double amount)
{
    balance-=amount;
}
void Account::addInterest(double interestRate)
{
    balance=balance*(1+interestRate);
}

另外,您似乎忘记了定义带参数的构造函数。

Account::Account( double initial_balance ) : balance( initial_balance ) {}