常量函数和引用

const function and references

本文关键字:引用 函数 常量      更新时间:2023-10-16

如果您注意到在以下函数中,它们都具有相同的 for 循环,用于搜索整数位置。Pop() 编译,但我收到与 const 限定符有关的 top() 错误。堆类继承自 eecs281heap,它存储一个函子 Comp 比较,其中 Comp 是类型名。讲师告诉我们访问函子的唯一方法是通过 this->(),所以我只是在这里寻找一些指导。谢谢

错误:将"const larger"作为"bool larger::operator()(int, int)"的"this"参数传递会丢弃限定符

这发生在 int main 中运行以下内容后。通过测试,我已经知道构造函数可以正常工作。

vector <int> data={10,2,13};
poorman_heap<int,larger> y(data.begin(),data.end());
template<typename TYPE, typename COMP>
void poorman_heap<TYPE, COMP>::pop() {
    int location=0;
    for(int i=1;i<data.size();i++){
        if(this->compare(data.at(i),data.at(location))){
            location=i;
        }
    }
    data.erase(data.begin()+location);
    return;
}
template<typename TYPE, typename COMP>
const TYPE& poorman_heap<TYPE, COMP>::top() const {
    int location=0;
    for(int i=1;i<data.size();i++){
        if(this->compare(data.at(i),data.at(location))){
            location=i;
        }
    }
    return data.at(location); 
}

附言更大的是

struct greater{
    bool operator()(int x,int y){
        return x>y;
    }
}

greater的调用运算符设为const运算符:

struct greater
{
    bool operator()(int x,int y) const
    {
        return x>y;
    }
}

这同样适用于this->compare决心的任何内容。它需要const.

比较器是非常量没有多大意义。

看起来问题是compare成员operator()声明为非const函数。由于听起来您没有能力更改它,因此您可以通过在 poorman_heap 中将其声明为mutable成员来获得所需的行为。

mutable关键字允许您区分"物理const"的对象(意味着实际字节不会更改)和"逻辑const"(意味着字节可能会更改,但对象的值在基本意义上没有不同)。基本上,这意味着为了const性的目的,某些东西"不算数"。我脑海中的经典例子是惰性初始化 - 你想在类const上声明get_value()函数,但你也不想浪费时间计算值,如果没有人使用它,所以你声明值mutable现在你可以计算它并在get_value()内分配给它,即使它是一个const成员函数。