使用pass-by-reference传递变量时接收引用值错误

时间:2018-03-05 03:11:53

标签: c++ const pass-by-reference

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

const int OPERAND_RANGE = 100;

void doOneProblem(char &op);
void doOneSet(char &op);
void generateOperands(int &num1, int &num2);
void calculateAnswer(int &num1, int &num2, int &answer, char &op);
void checkAnswer(int num1, int num2, int &answer, int &userAnswer, char &op);

int main() {

    srand(static_cast<unsigned>(time(0)));
    doOneSet('+');

}

void generateOperands(int &num1, int &num2) {

    num1 = rand() % (OPERAND_RANGE + 1);
    num2 = rand() % (OPERAND_RANGE + 1);

}

void calculateAnswer(int &num1, int &num2, int &answer, int &userAnswer, char &op) {

    if (op == '+') {
        answer = num1 + num2;
    } else if (op == '-') {
        answer = num1 - num2;
    } else if (op == '*') {
        answer = num1 * num2;
    } else if (op == '/') {
        answer = num1 / num2;
    } else {
        cout << "Not an accepted operator.";
    }

}

void doOneProblem(char &op) {

    int num1, num2, answer, userAnswer;
    char op;

    generateOperands(num1, num2);
    calculateAnswer(num1, num2, answer, userAnswer, op);
    checkAnswer(num1, num2, answer, userAnswer, op);


}

void checkAnswer(int num1, int num2, int &answer, int &userAnswer, char &op) {

    cout << "What is " << num1 << " " << op << " " << num2 << "?: " << endl;
    cin >> userAnswer;

    if (userAnswer == answer) {
        cout << "Correct!" << endl;
    } else {
        cout << "Incorrect" << endl;
    }


}

void doOneSet(char &op) {

    for (int i = 0; i < 5; i++) {

        doOneProblem(op);

    }


}

嘿大家,我正在做一些传递引用变量的练习。当我在main中调用函数doOneSet时,我得到错误:

initial value of reference to non-const must be an lvalue

我的目标是将doOneSet中的operator(op)变量一直传递回calculateAnswer()函数,该函数应根据输入的char确定答案。

错误讯息:

a7_1.cpp:18:5: error: no matching function for
      call to 'doOneSet'
    doOneSet('+');
    ^~~~~~~~
a7_1.cpp:10:6: note: candidate function not
      viable: expects an l-value for 1st
      argument
void doOneSet(char &op);
     ^
1 error generated.

1 个答案:

答案 0 :(得分:0)

执行此操作时:

doOneSet('+');

关于此功能:

void doOneProblem(char &op);

您正在对rvalue进行非const引用。编译器如何知道在该函数中你不会这样做:

op = 10;

如果你这样做了,会发生什么? rvalue op存在于哪里,你会改变什么?解决方案是正确指定函数的原型。对于这种情况,它应该是:

 void doOneProblem(char op);