免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1116 | 回复: 0
打印 上一主题 下一主题

构造函数后跟冒号 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-22 08:51 |只看该作者 |倒序浏览
1、Problom

class GeoNeighborsTimer : public TimerCallback {    
public:
GeoNeighborsTimer(GeoRoutingFilter *agent) : agent_(agent) {};
~GeoNeighborsTimer() {};
int expire();

GeoRoutingFilter *agent_;
};

只知道在类后加冒号后跟继承的父类,可这构造函数后跟一个冒号,后边又有类的成员,又有构造函数的参数,这是什么意思呢?

2、Anwser

构造函数后跟冒号
表示先对冒号后的类成员(参数中的哪个)进行初始化,然后做为冒号前类的成员。

class Student {
public:
Student() {}
Student( const string& nm, int sc = 0 )
: name( nm ), score( sc ) {}
//这个跟name=nm ;score=sc;语句效果一样

private:
string name;
int score;
};

关于什么时候得这么用?是不是必须得这么用?和是不是只能用在构造函数?待考证 。。。。

from: c++ primer
Constructors 构造函数

When we create an object of a class type, the compiler automatically uses a constructor (Section 2.3.3, p. 49) to initialize the object. A constructor is a special member function that has the same name as the class. Its purpose is to ensure that each data member is set to sensible initial values.

创建一个类类型的对象时,编译器会自动使用一个构造函数(第 2.3.3 节)来初始化该对象。构造函数是一个特殊的、与类同名的成员函数,用于给每个数据成员设置适当的初始值。

A constructor generally should use a constructor initializer list (Section 7.7.3, p. 263), to initialize the data members of the object:

构造函数一般就使用一个构造函数初始化列表(第 7.7.3 节),来初始化对象的数据成员:

// default constructor needed to initialize members of built-in type
Sales_item(): units_sold(0), revenue(0.0) { } The constructor initializer list is a list of member names and parenthesized initial values. It follows the constructor's parameter list and begins with a colon.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP