构造函数

#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();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值