【问题标题】:error: non-member function ‘int indice_max(const std::vector<double>&)’ cannot have cv-qualifier错误:非成员函数“int indice_max(const std::vector<double>&)”不能有 cv 限定符
【发布时间】:2020-11-30 22:16:06
【问题描述】:

我对函数 indice_max 有一个错误“不能有 cv 限定符”,我不明白为什么,我不会随时修改向量 v

#include <iostream>
#include <vector>
#include <algorithm>

using std::vector;

int indice_max(const vector<double> & v) const{
    int indice =0;
    double max = v[0];
    for(int i=0; i<v.size(); i++){
        if(v[i]>max){
            max = v[i];
            indice = i;
        }
    }
    return indice;
}

【问题讨论】:

  • 不能将非成员函数声明为const
  • int indice_max(const vector&lt;double&gt; &amp; v) const 第二个const 声明 this 是其成员函数的类的变量在逻辑上对于该函数是恒定的。如果这 not 是一个成员函数,那就没有意义了。因此,您不能将非成员函数声明为 const
  • 这可能会回答你的问题:stackoverflow.com/questions/3474119/…

标签: c++


【解决方案1】:

const 限定符(在函数签名之后)在类成员函数承诺不更改任何先前分配给数据成员的值时使用。

在给定的代码中,没有类及其私有数据成员。因此,在这种情况下使用它没有任何意义,并且不允许在非成员函数上使用类型限定符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2021-05-05
    • 2020-03-24
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多