C++ 语义问题:"'use of undeclared identifier 'balance'"

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

本文关键字:undeclared identifier balance of 语义 问题 C++ use      更新时间:2023-10-16

我是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是Account类的double类型的数据成员。

或者你可以写

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

如果函数是类成员函数,那么所有这些函数定义都必须看起来至少像

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 ) {}