#include<iostream>
using namespace std;
class BankAccount
{
public:
BankAccount(int dollars,int cents,double rate) //初始化构造函数
BankAccount(int dollars,double rate) //函数重载
BankAccount(); //默认构造函数
void update();
double get_rate();
double get_balance(); //返回当前账户余额
void output(ostream & outs);
private:
double balance;
double interest_rate;
double fraction(double pecent); //将百分数转变为小数;
};
int main();
{
BankAccount account1(100,2,3),account2; //这个声明导致对默认构造函数的调用 注意没有使用圆括号;
cout<<"account1 initialized as following :\n";
account1.output(cout);
cout<<"account2 initialized as following :\n";
account2.output(cout);
account=BankAccount(999,99,5.3); //对构造函数BankAccount::BankAccount的显示调用;
cout<<"account1 reset to the followings :\n";
account1.output(cout);
return 0;
}
BankAccount ::BankAccount(int dollars,int cents,double rates)
{
if((dollars<0)||(cents<0)||(rate<0))
{cout<<"illegal values for money or interest rate\n";
exit(1);}
balance=dollars+0.01*cents;
insterest_rate=rate;
}
BankAccount::BankAccount(int dollars,double rate)
{
if((dollars<0)||(rate<0))
{cout<<"illegal values for money or interest rate \n";
exit(1);}
balance=dollars;
interest_rate=rate;
}
BankAccount::BankAccount():balance(0),interest_rate(0.0)
{
}
构造函数是一个类的成员函数,名称与类相同,声明类的一个对象时会自动调用构造函数,用于初始化对象,构造函数必须与定义它的那个类同名。
c++并非 总是为你定义的类 提供构造函数。如果没有提供构造函数,编译器将生成一个什么事情都不做的默认构造函数,声明该类的对象是会调用该函数,相反如果至少为类提供了一个构造函数的定义,c++就不会生成其他构造函数。
每次声明那个类的对象时候c++会查找一个默认的构造函数,如果没有c++徒劳而返。
class sample
{
public:
sample(int parameter1,double parameter2);
void set_sample();
private:
int data1;
double data2;
}
//下面语句合法
//sample my_object(7,77);
//但是下面违法
//sample your_project;
//上面代码加一个默认构造函数 sample();
//就可以了。
调用无参数的构造函数时候没不能加圆括号比如 sample your_object();