簡體   English   中英

將const傳遞給具有非const參數的函數

[英]Passing const to function with non-const parameter

我正在關注加速的C ++書,但是我對它們提供的源代碼感到困惑。 我的困惑涉及函數double grade(double midterm, double final, const vector<double>& hw)double median(vector<double> vec) 它在注釋中說,由於中median函數會復制,因此grade函數不會復制其參數。 為什么會這樣? 根據我的理解,您無法將const傳遞給非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這里是一個常量引用一個載體,其被傳遞到median 雖然確實不能通過const引用修改對象,但是仍然可以通過const引用對其進行復制。 因此,由於median要求更改vector (通過對vector進行排序),因此它會自行復制(此副本將在內部隱式創建)並進行排序。

為什么會這樣? 根據我的理解,您無法將const傳遞給非const,因為這需要進行寫訪問。

是的,不是,不能寫入const變量是正確的,但這不是這里發生的情況。

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

這里的中median要求對我們有用。 median期望一個std::vector ,並且編譯器在后台將其傳遞給它。 它在const &引用的向量上進行復制,並將該副本傳遞給median 記住,編譯器只需要讀取訪問權就可以復制,而不需要寫入,這正是hw給我們的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM