一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

const成员变量的初始化详解

时间:2022-06-25 04:59:04 编辑:袖梨 来源:一聚教程网

const 成员变量的初始化
const的成员变量只能在类的构造函数初始化,如下编译报错

//const.h#includeclass cconst{public:    cconst();    void

print()    {        std::cout<<"----"<

const int cs;};
//const.cpp#include"const.h"cconst::cconst(){}int main(int argc, char*

argv[]){    cconst* a = new cconst();    a->print();    return 0;}


编译报错error c2758: 'cs' : must be initialized in constructor

base/member initializer list

将const.cpp修改为:


#include"const.h"cconst::cconst(){    cs = 0;}int main(int argc, char*

argv[]){    cconst* a = new cconst();    a->print();    return 0;}

仍然报错:

error c2758: 'cs' : must be initialized in constructor base/member

initializer list

修改为下面形式后,正常:


#include"const.h"cconst::cconst():cs(0){    //cs = 0;}int main(int argc,

char* argv[]){    cconst* a = new cconst();    a->print();    return 0;}

热门栏目