请教几个小问题

时间:2008-05-10 10:58:37   来源:论坛整理  作者:  编辑:chinaitzhe
//此为静态数据成员和静态成员函数的使用例子,有几处看不明白(????).请高手指点!
#include <iostream.h>
class goods
{
private:
static int totalWeight;
int weight;
public:
goods(int w)
{
weight=w;
totalWeight =w;
}
goods(const goods &gd) //这句参数里为什么要这样???
{
weight=gd.weight;
totalWeight =weight;
}
~goods()
{
totalWeight-=weight;
}
static int getTotal()
{
return totalWeight;
}
};
int goods::totalWeight=0;
void main()
{
int w;
cout < <"the initial weight of goods:" < <goods::getTotal() < <endl;
cin>>w;
goods g1(w);
cin>>w;
goods g2(w);
goods g3(g2);
cout < <"the goods weight of goods:" < <goods::getTotal() < <endl;
}
网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



#include <iostream.h> 

class goods 

{ 

private: 

static int totalWeight; 

int weight; 

public: 

goods(int w) 

{ 

weight=w; 

totalWeight =w; 

} 

goods(const goods &gd)    //1.必须是引用,否则在调用拷贝函数的时候,又会去复制构造一个对象,就是调用本身了

//2.常引用和普通引用不好说,最好是常引用,保证原来的不被修改

{ 

weight=gd.weight; 

totalWeight =weight; 

} 

~goods() 

{ 

totalWeight-=weight; 

} 

static int getTotal() 

{ 

return totalWeight; 

} 

}; 

int goods::totalWeight=0; 

void main() 

{ 

int w; 

cout < <"the initial weight of goods:" < <goods::getTotal() < <endl; 

cin>>w; 

goods g1(w); 

cin>>w; 

goods g2(w); 

goods g3(g2); 

cout < <"the goods weight of goods:" < <goods::getTotal() < <endl; 

}


网友回复:
引用 1 楼 baihacker 的回复:
goods(const goods &gd) //1.必须是引用,否则在调用拷贝函数的时候,又会去复制构造一个对象,就是调用本身了
//2.常引用和普通引用不好说,最好是常引用,保证原来的不被修改

嗯!
关键字:请教,几个,问题,

相关文章

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面