通关旅

softgamer 的痕迹
posts - 12, comments - 0, trackbacks - 0, articles - 1

C++体会 -- 初始化类的常量数据成员

Posted on 2007-02-09 22:19 softgamer 阅读(746) 评论(0)  编辑  收藏 所属分类: 学习日志
如果你想初始化一个类中的常量数据成员,只能用一种方法,在类的构造函数后加一个":",然后初始化那些常量数据成员,
以逗号分割。

#include <iostream>

using std::cout;
using std::endl;

class Test
{
  public:
    Test(int i = 0, int j = 1 );
    void addon() { count += idx; }
    void print() const;
  private:
    int count;
    const int idx;
    const int idy;
};

Test::Test( int i, int j )
  :idx( j, i ), idy( j, j )
{
   count = j;
}

void Test::print() const
{
   cout << "count= " << count
        <<", idx = " << idx
        <<", idy = " << idy
        << endl;
}

int main()
{
    Test Test1( 20, 7 );
    cout << "Before doing addon: ";
    Test1.print();
    for ( int k = 0; k < 3; k++ )
    {
       Test1.addon();
       cout << "After addon " << k + 1 << ":";
       Test1.print();
    }
    return 0;
}

result:
Before doing addon: count= 7, idx = 20, idy = 7
After addon 1:count= 27, idx = 20, idy = 7
After addon 2:count= 47, idx = 20, idy = 7
After addon 3:count= 67, idx = 20, idy = 7



只有注册用户登录后才能发表评论。


网站导航: