c ++ const错误

时间:2012-08-10 05:12:47

标签: c++ const

    bool check_integrity( int pos ) const
    {
        if (( pos <= 0 ) || ( pos > max_seq ) || ( pos  >= _length + _beg_pos ))
        {
             cerr << "!! invalid position: " << pos
                  << " Cannot honor request\n";
             return false;
        }

        if ( _isa == ns_unset ) 
        {
             cerr << "!! object is not set to a sequence."
                  << " Please set_sequence() and try again!\n";
             return false;
        }

        if ( pos > _elem->size()){
             cout << "check_integrity: calculating "
                  << pos - _elem->size() << " additional elements\n";
             ( this->*_pmf )( pos );
        }

        return true;
    }


    public:
        typedef void (num_sequence::*PtrType)( int );
    private:
        PtrType    _pmf;
  

上面的代码片段是“num_sequence”类的一部分。我得到了一个错误   以下一行:

( this->*_pmf )( pos );
  

错误是:'const num_sequence * const this'错误:对象有   与成员函数

不兼容的类型限定符

谢谢!

3 个答案:

答案 0 :(得分:4)

check_integrity是一个const函数,因此函数调用也必须是const,因此调用PtrType函数也必须是const。< / p>

试试这个:

typedef void (num_sequence::*PtrType)( int ) const;

注意:我没有编译这个:)只是大声思考。

答案 1 :(得分:3)

您正在尝试将_pmf指向的非const成员函数调用为常量对象*this。这违反了const-correctness规则。

PtrType声明为

typedef void (num_sequence::*PtrType)( int ) const;

或从const功能

中删除check_integrity
bool check_integrity( int pos )
{
   ...

这个或那个。在这种情况下,您没有为其他人提供足够的信息来决定哪个是正确的。

答案 2 :(得分:1)

您需要更改

typedef void (num_sequence::*PtrType)( int );

typedef void (num_sequence::*PtrType)( int ) const;

因为您从const函数

调用函数