一道C++的题~想了很久还是不会

来源:百度知道 编辑:UC知道 时间:2024/06/21 02:21:06
2. 根据下面的输出和主函数语句,定义构造函数。(2分)
void main()
{
battery bat1;
cout<<"电池bat1的储电量:"<<bat1.cloumn<<"毫安"<<endl
<<"电池bat1的重量:"<<bat1.heavy<<"克"<<endl;

battery bat2(100.0,20000);
battery* pt = NULL;
pt = &bat2;
cout<<"电池bat2的储电量:"<<pt->cloumn<<"毫安"<<endl
<<"电池bat2的重量:"<<pt->heavy<<"克"<<endl;
}
希望具体一点我是新手不太明白........

//怎么搞得,一添加注释,就变成第二个了!
class battery
{
public:
float cloumn;
int heavy;
battery()//无参构造函数
{
cloumn = 1000;
heavy = 300;
}
battery(float num1,int num2)//重载一个带参数的构造函数分别用来具体赋值用
{
cloumn = num1;
heavy = num2;
}
//...
}

就是让你重载一个构造函数吧。
class battery
{
private:
float heavy;
int cloumn;
public:
battery()
{
heavy = 400.0;
cloumu = 900; //也可以是任意的其他值
}
battery(float h, int c)
{
heavy = h;
cloumu = c;
}
};