游戏开发论坛

 找回密码
 立即注册
搜索
查看: 2751|回复: 3

[C++] 请解释为什么两种输出结果不一样

[复制链接]

3

主题

32

帖子

36

积分

注册会员

Rank: 2

积分
36
发表于 2007-11-14 09:41:00 | 显示全部楼层 |阅读模式
/*
IdentityGenerator的作用是生成ID号, 调用operator () 时,从头开始查找第一个没有被使用的ID,然后返回此ID
unregister(int id)的作用就是注销某id号,
*/

// template class IdentityGenerator
template <size_t UpperBound>
class IdentityGenerator {
public :
        void unregister(int id);
        int operator() ();
        static const int invalid_id = -1;
private:
        bitset<UpperBound> used;
};

template <size_t UpperBound>
const int IdentityGenerator<UpperBound>::invalid_id;

template <size_t UpperBound>
int IdentityGenerator<UpperBound>:perator() () {
        if (used.count() == UpperBound)
                return invalid_id;
        int i = 0;
        while (used) i++;
        used = true;
        return i;
}

template <size_t UpperBound>
void IdentityGenerator<UpperBound>::unregister(int id)
{
        assert((id >= 0) && (id < UpperBound));
        used[id] = false;
}


IdentityGenerator<1024> idGenerator;

int main()
{
        for (int i = 0; i<5; i++)
                cout << idGenerator() << endl;

        idGenerator.unregister(3);
        idGenerator.unregister(2);

        // 为什么下面两种输出方式结果不一样
        cout << idGenerator() << endl;
        cout << idGenerator() << endl;
        cout << idGenerator() << endl;

/* !跟想像中的输出不一样!
前面的for生成5个id,接着注销id号3和2
接着再生成3个id时,为什么两种输出方式输出结果不一样
*/
        /*
        cout << idGenerator() << endl
                << idGenerator() << endl
                << idGenerator() << endl;
                */
}

第一种输出为:
0
1
2
3
4
2
3
5
是我想要的结果

为什么第二种输出却是这样的?
0
1
2
3
4
5
3
2

3

主题

32

帖子

36

积分

注册会员

Rank: 2

积分
36
 楼主| 发表于 2007-11-14 22:33:00 | 显示全部楼层

Re:[C++] 请解释为什么两种输出结果不一样

你说的这个我明白
我觉得你说这个跟那个不太一样

operator ()就相当于一个函数调用,用cout输出每次的返回值

cout << idGenerator() << endl // 找到第一次没有使用的id
<< idGenerator() << endl
<< idGenerator() << endl;

想像中应该就相当于
cout << 2 << endl
3 << endl
5 << endl;

那为什么直接输出
cout << 2 << endl
3 << endl
5 << endl;
不是
5
3
2
而是
2
3
5

3

主题

32

帖子

36

积分

注册会员

Rank: 2

积分
36
 楼主| 发表于 2007-12-29 17:15:00 | 显示全部楼层

Re:[C++] 请解释为什么两种输出结果不一样

。。。

23

主题

63

帖子

68

积分

注册会员

Rank: 2

积分
68
发表于 2008-1-2 10:54:00 | 显示全部楼层

Re:[C++] 请解释为什么两种输出结果不一样

最后一个 idGenerator() 先调的
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2026-1-23 23:53

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表