1

我有一个简单的 const 方法想要生成一个随机数

int Object::const_method() const {
    std::tr1::uniform_int<int> uni(0,100);
    // do some calculation
   return result;
}

这会导致您的标准(如果已模板化)const 违规错误

/usr/lib/gcc/x86_64-unknown-linux-gnu/4.5.1/../../../../include/c++/4.5.1/tr1/random.tcc:910:4:错误: 传递 'const std::tr1::mersenne_twister' 作为 'result_type std::tr1::mersenne_twister<_UIntType, __w, __n, __m, __r, __a, __u, __s, __b, __t, __c, __l>::operator()() [with _UIntType = long unsigned int, int __w = 32, int __n = 624, int __m = 397, int __r = 31, _UIntType __a = 2567483615ul, int __u = 11, int __s = 7, _UIntType __b = 2636928640ul, int __t = 15, _UIntType __c = 4022730752ul, int __l = 18, result_type = long unsigned int]' 丢弃限定符

这在没有const_caston的情况下可行this吗?

4

1 回答 1

1

使您的 mersenne_twister 对象在您的类中可变。没有看到你所有的代码,(尤其是 do_something 部分),我们不能确定,但​​我猜你在你的类中有一个 mersene_twister 类型的对象,你正在使用一个不是 const 函数本身的函数. 这会导致您的课程出现错误,因为您的 const 函数正在调用 merseen_twister 上的一个函数,该函数可能会更改它,从而违反了您的 const 签名。

// I'm using this as an example.  Yours may differ
typedef std::mersenne_twister<unsigned int, 32, 624, 
    397, 31, 0x9908b0df, 11, 7, 0x9d2c5680, 
    15, 0xefc60000, 18> MerTwister;

class Object 
{
    public:

    int Object::const_method() const 
    {
       std::tr1::uniform_int<int> uni(0,100);

       // do some calculation using the MerTwister object
       return result;
    }


    private:
    mutable MerTwister twister;
};
于 2010-11-15T00:06:46.240 回答