构造函数初始化为0使用 [英] Constructor initialization to 0 use

查看:497
本文介绍了构造函数初始化为0使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用构造函数初始化为0(零),如下面的程序



我是什么尝试过:



当我运行以下程序时,sa总是0,不应该是





i wnt to know the use of constructor initialization to 0(zero) as in the following program

What I have tried:

when I run the following program, sa is always 0 which should not be


class bank
{
private:
double a,sa;
char ac,c,s;
public:

void deposit(double amount, char account);
};
void bank::deposit(double amount, char account)
{
a=amount,
ac=account;
if (ac=='s')
{
sa=sa+a;
cout<<sa;

}
}
main()
{
char account;
double amount;

clrscr();
bank b;
cout<<"enter account type: ";
cin>>account;
cout<<"enter amount:" ;
cin>>amount;
b.deposit(amount, account);
getch();
}



但是当我添加


but when i add

/*bank()
{
sa=0;
}*/



如以下程序中所示,它显示正确的sa,即以下程序显示正确的结果。


as in the following program, it shows correct sa i.e. the following program shows the correct result.

class bank
{
private:
double a,sa;
char ac,c,s;
public:
bank()
{
sa=0;
}
void deposit(double amount, char account);
};
void bank::deposit(double amount, char account)
{
a=amount,
ac=account;
if (ac=='s')
{
sa=sa+a;
cout<<sa;

}
}
main()
{
char account;
double amount;

clrscr();
bank b;
cout<<"enter account type: ";
cin>>account;
cout<<"enter amount:" ;
cin>>amount;
b.deposit(amount, account);
getch();
}





所以,

任何人都可以启发我,有什么用途: -



so,
can anyone enlighten me, what is the use of:-

bank()
/*{
sa=0;
}*/

推荐答案

它被称为数据成员初始化并且是构造函数的目的(它们应该设置对象的初始staate)。

未初始化的数据成员可能包含垃圾。
It is called data member initialization and is the very purpose of constructors (they should set the initial staate of the object).
A not initialized data member may contain garbage.


未分配的值变量未定义。

所以当你说 double sa; sa 中的值将是分配给它的内存中留下的任何东西。



当你创建一个构造函数并进行赋值时,该值设置为0.



所以你展示构造函数的方式,转换为 -

The value in an unassigned variable is undefined.
So when you say double sa; the value in sa will be whatever is left over in the memory allocated to it.

When you create a constructor and do assignment, the value is set to 0.

So the way you have shown the constructor, translates to -
double sa;
sa = 0;


这篇关于构造函数初始化为0使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆