程序让生活更美好

半亩方塘 天光云影

  C++博客 ::  :: 新随笔 :: 联系 ::  :: 管理 ::
  55 随笔 :: 4 文章 :: 202 评论 :: 0 Trackbacks

冒号初始化列表的一个作用

   我们在创建C++类的时候,如果类中有const类型的变量,那么这个值的初始化就是一个问题,可以看下面一段代码:

#include  < iostream >
using   namespace  std;

class  Test
{
public :
    Test(
int  i)
    {
        identifier 
= 1 ;//这里错误
        cout
<< " Hello  " << identifier << " \n " ;
    } 
    
~ Test()
    {
        cout
<< " Googbye  " << identifier << endl;
    }
private :
    
const   int  identifier;
};

int  main()
{
    Test theWorld(
1 );
    
return   0 ;
}
在VC6.0下编译的时候,无法通过,编译器提示如下
error C2758: 'identifier' : must be initialized in constructor base/member initializer list
see declaration of 
'identifier'
error C2166: l
-value specifies const object

   可以看见在普通构造函数方式下是不能初始化const类型的,它是个左值。
   那么我们怎么解决这个问题呢?这里就是我要讲的,使用冒号初始化列表方式。
  再看下面的代码:
#include <iostream>
using namespace std;

class Test
{
public:
    Test(
int i):identifier(i)//冒号初始化列表
    {
        cout
<<"Hello "<<identifier<<"\n";
    } 
    
~Test()
    {
        cout
<<"Googbye "<<identifier<<endl;
    }
private:
    
const int identifier;
};

int main()
{
    Test theWorld(
1);
    
return 0;
}
     上面这个代码使用了冒号程序化列表,程序可以编译通过,这样我们就可以在对象创建的时候再给const类型的类变量赋值了。
    输出结果是:
Hello 1
Goodbye 
1

此文完。
posted on 2006-07-20 16:46 北风之神007 阅读(2441) 评论(0)  编辑 收藏 引用 所属分类: c/c++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理