我正在尝试从 Deitel 的书中做另一个练习。该程序计算每月利息并打印每个储户的新余额。由于该练习是与动态内存相关的章节的一部分,因此我使用“new”和“delete”运算符。出于某种原因,我收到以下两个错误:
LNK2019:函数 ___tmainCRTStartup 中引用的未解析外部符号 WinMain@16
致命错误 LNK1120:1 个未解决的外部问题
这是类头文件。
//SavingsAccount.h
//Header file for class SavingsAccount
class SavingsAccount
{
public:
static double annualInterestRate;
SavingsAccount(double amount=0);//default constructor intialize
//to 0 if no argument
double getBalance() const;//returns pointer to current balance
double calculateMonthlyInterest();
static void modifyInterestRate(double interestRate):
~SavingsAccount();//destructor
private:
double *savingsBalance;
};
包含成员函数定义的 Cpp 文件
//SavingsAccount class defintion
#include "SavingsAccount.h"
double SavingsAccount::annualInterestRate=0;//define and intialize static data
//member at file scope
SavingsAccount::SavingsAccount(double amount)
:savingsBalance(new double(amount))//intialize savingsBalance to point to new object
{//empty body
}//end of constructor
double SavingsAccount::getBalance()const
{
return *savingsBalance;
}
double SavingsAccount::calculateMonthlyInterest()
{
double monthlyInterest=((*savingsBalance)*annualInterestRate)/12;
*savingsBalance=*savingsBalance+monthlyInterest;
return monthlyInterest;
}
void SavingsAccount::modifyInterestRate(double interestRate)
{
annualInterestRate=interestRate;
}
SavingsAccount::~SavingsAccount()
{
delete savingsBalance;
}//end of destructor
最后结束驱动程序:
#include <iostream>
#include "SavingsAccount.h"
using namespace std;
int main()
{
SavingsAccount saver1(2000.0);
SavingsAccount saver2(3000.0);
SavingsAccount::modifyInterestRate(0.03);//set interest rate to 3%
cout<<"Saver1 monthly interest: "<<saver1.calculateMonthlyInterest()<<endl;
cout<<"Saver2 monthly interest: "<<saver2.calculateMonthlyInterest()<<endl;
cout<<"Saver1 balance: "<<saver2.getBalance()<<endl;
cout<<"Saver1 balance: "<<saver2.getBalance()<<endl;
return 0;
}
我花了一个小时试图解决这个问题,但没有成功。