常量函数和引用
const function and references
如果您注意到在以下函数中,它们都具有相同的 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
成员函数。
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 无法将右值引用函数与 GCC 匹配
- C ++引用函数参数似乎包含原始对象的副本,而不是充当"real reference"
- 通过引用函数传递指针参数是什么意思?
- 常量引用函数参数的地址何时唯一?
- 我想了解为什么在这个例子中使用引用函数?或者引用在c++函数中的重要性
- C++ 通过引用函数传递数组,但内容保持不变
- 用数组或指针引用函数?
- 引用函数如何"int &foo();"工作?
- 常量引用函数参数:是否可以禁止临时对象?
- 计算在代码中引用函数的次数
- <initializer_list> 引用函数
- 字符串引用(函数)的差异
- 在类中引用函数时的"No Matching Function for Call"
- 无法通过引用函数"calcValues"中"firstNum"和"secondNum"变量来更改值
- 尝试引用已删除的函数(不引用函数)
- 引用函数指针
- 引用函数按值和自动返回
- 为什么我们可以取消引用函数指针
- 通过引用函数传递值的目的是什么