c++ - 将 const 传递给具有非常量参数的函数

标签 c++ reference constants

我正在关注加速的 C++ 书籍,但我对他们提供的源代码感到困惑。我的困惑涉及函数double grade(double midterm, double final, const vector<double>& hw)double median(vector<double> vec) . 它在评论中说 grade函数不复制它的参数,因为 median功能确实如此。为什么会这样? 据我了解,您不能将 const 传递给非常量,因为需要写访问权限。

代码如下:

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::domain_error;
using std::endl;
using std::istream;
using std::ostream;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;

// compute the median of a `vector<double>'
// note that calling this function copies the entire argument `vector'
double median(vector<double> vec)
{
#ifdef _MSC_VER
    typedef std::vector<double>::size_type vec_sz;
#else
    typedef vector<double>::size_type vec_sz;
#endif

    vec_sz size = vec.size();
    if (size == 0)
        throw domain_error("median of an empty vector");

    sort(vec.begin(), vec.end());

    vec_sz mid = size/2;

    return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}

// compute a student's overall grade from midterm and final exam grades and homework grade
double grade(double midterm, double final, double homework)
{
    return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}

// compute a student's overall grade from midterm and final exam grades
// and vector of homework grades.
// this function does not copy its argument, because `median' does so for us.
double grade(double midterm, double final, const vector<double>& hw)
{
    if (hw.size() == 0)
        throw domain_error("student has done no homework");
    return grade(midterm, final, median(hw));
}

// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
    if (in) {
        // get rid of previous contents
        hw.clear();

        // read homework grades
        double x;
        while (in >> x)
            hw.push_back(x);

        // clear the stream so that input will work for the next student
        in.clear();
    }
    return in;
}


int main()
{
    // ask for and read the student's name
    cout << "Please enter your first name: ";
    string name;
    cin >> name;
    cout << "Hello, " << name << "!" << endl;

    // ask for and read the midterm and final grades
    cout << "Please enter your midterm and final exam grades: ";
    double midterm, final;
    cin >> midterm >> final;

    // ask for the homework grades
    cout << "Enter all your homework grades, "
            "followed by end-of-file: ";

    vector<double> homework;

    // read the homework grades
    read_hw(cin, homework);

    // compute and generate the final grade, if possible
    try {
        double final_grade = grade(midterm, final, homework);
        streamsize prec = cout.precision();
        cout << "Your final grade is " << setprecision(3)
             << final_grade << setprecision(prec) << endl;
    } catch (domain_error) {
        cout << endl << "You must enter your grades.  "
            "Please try again." << endl;
        return 1;
    }

    return 0;
}

最佳答案

看看这一行:

return grade(midterm, final, median(hw));

hw 这里是一个 vector 的 const 引用,它被传递给 median。虽然您不能通过 const 引用修改对象,但您仍然可以通过 const 引用复制它。因此,由于 median 需要更改 vector(通过对其进行排序),它会为自己制作一个拷贝(该拷贝将在幕后隐式创建)并对其进行排序.

关于c++ - 将 const 传递给具有非常量参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43114216/

相关文章:

JavaScript 数组值到变量

c# - 如何对 Windows API 常量进行分组

C 语法 : Is the following 'extern volatile const' behavior consistent among C compilers?

c++ - 在这种情况下不使用 'protected' 的任何理由(cpp、c++、oop)

c++ - 将 gsl_ran_hypergeometric_pdf(k, n1, n2, t) 翻译成 boost::math::hypergeometric_distribution

c++ - 函数的返回值未被识别为左值

c - 有什么方法可以保护变量在运行时在 C 中被修改吗?

c++ - 移动构造函数模板省略

c++ - 一整套参数的模板特化

结构初始化的C结构