64,642
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
# include <iostream>
# include <string>
using namespace std;
class Account
{
private:
string name;
double balance;
static double rate;
public:
Account(string n,double b): name(n), balance(b){}
Account(){}
~Account() {}
Account(const Account& ac):name(ac.name),balance(ac.balance){}
Account& operator = (const Account& ac);
void Display () const;
double passyear(int);
static void SetRate(double);
};
Account& Account:: operator = (const Account& ac)
{
name = ac.name;
balance = ac.balance;
rate = ac.rate;
return *this;
}
void Account::Display() const
{
cout<<"name "<<name<<" balance "<<balance<<endl;
}
void Account::SetRate(double r)
{
rate = r;
}
double Account:: passyear(int)
{
balance = (1 + rate) * balance;
return balance;
}
double Account::rate=0;
int main()
{
Account::SetRate(0.35); //设置年利率
Account ac1("ligang",1000.0); //创建账户名ligang, 余额为1000.0的帐户
Account ac2(ac1);
Account ac3;
ac3=ac1=ac2;
ac3.passyear(1); //计算1年后的余额
ac1.Display(); //显示账户名及余额
ac2.Display();
ac3.Display();
return 0;
}
正确代码如上.
原代码有几个错误
1.声明默认构造函数但未定义
2.静态成员未在类外事先初始化
3.复制构造函数无初始化列表,而你又ac3=ac1=ac2造成无意义的实现
# include <iostream>
# include <string>
using namespace std;
class Account
{
private:
string name;
double balance;
static double rate;
public:
Account(string n,double b): name(n), balance(b){}
Account(){}//这里没有定义。。
~Account() {}
Account(const Account& ac){}
Account& operator = (const Account& ac);
void Display () const;
double passyear(int);
static void SetRate(double);
};
double Account::rate;//static成员要类外定义
Account& Account:: operator = (const Account& ac)
{
name = ac.name;
balance = ac.balance;
rate = ac.rate;
return *this;
}
void Account::Display() const
{
cout<<"name "<<name<<" balance "<<balance<<endl;
}
void Account::SetRate(double r)
{
rate = r;
}
double Account:: passyear(int)
{
balance = (1 + rate) * balance;
return balance;
}
int main()
{
Account::SetRate(0.35); //设置年利率
Account ac1("ligang",1000.0); //创建账户名ligang, 余额为1000.0的帐户
Account ac2(ac1);
Account ac3;
ac3=ac1=ac2;
ac3.passyear(1); //计算1年后的余额
ac1.Display(); //显示账户名及余额
ac2.Display();
ac3.Display();
return 0;
}