C++ 函数,通过引用传递

C++ functions, pass by reference

我在调用函数时将参数作为引用传递时遇到问题。 我们将使用以下指令构建程序:

Complete the program above by writing the function definitions and the function prototypes for the following functions:

displaymenu This function accepts num1 and num2 as arguments passed by reference and returns a character as output. The function displays the menu and accepts as user-given inputs the following:

A num1
B num1 num2
Q

checkeven This function returns TRUE if the argument is even. Otherwise the function returns FALSE.

divisible This function returns TRUE if the first argument, num1, is divisible by the second argument, num2.

到目前为止这是我的代码并且在传递参数时出错。

#include <iostream>

using namespace std;
int num1, num2 = 0;
char displaymenu(int num1, int num2);
bool checkeven (int num1);
bool divisible (int num1, int num2);

int main(){
    int num1, num2 = 0;
    char choice;
    do{
       choice = displaymenu(num1,num2);    
       if (choice == 'A'){
           if (checkeven(num1))
               cout << num1 << " is even." << endl;
           else 
                cout << num1 << " is odd." << endl;
       }          
       else if (choice == 'B'){
          if (divisible(num1, num2))
              cout << num1 << " is divisible by " << num2 << endl;
          else
              cout << num1 << " is not divisible by " << num2 << endl;
       }
       else if (choice == 'Q')
            cout << "Bye!" << endl;
       else 
            cout << "Illegal input" << endl;
       
    }while (choice != 'Q');
    return 0;
}

char displaymenu(int &num1 = num1, int &num2 = num2){
    char choice;
    cout << '+' << "______________________________" << '+' <<endl;
    cout << '|'<<"Choose an option: " <<"            |"<<endl; 
    cout << '|'<<"    A: Check if even          |" <<endl;
    cout << '|'<<"    B: Check if divisible     |" <<endl;
    cout << '|'<<"    Q: Quit                   |" <<endl;
    cout << '+' << "______________________________" << '+' <<endl;
    cout << "   Reply: ";
    cin>> choice>> num1>> num2;
    return choice;
    }

bool checkeven(int num1){
    if (num1 % 2 == 0)
        return true;
    else
        return false;
    } 

bool divisible(int num1, int num2){
    
    if (num1 % num2 == 0)
        return true;
    else
        return false;
    }

我不会用完整的解决方案来回答(你可以自由地改进你的问题,以便以后得到更好的答案),但关于问题标题,这里有一些提示。

您的声明

char displaymenu(int num1, int num2);

和你的定义

char displaymenu(int &num1 = num1, int &num2 = num2)

应该有相同的签名。为了传递引用,将声明更改为

char displaymenu(int &num1, int &num2);

此外,由于您通过引用传递值,因此您应该删除 using namespace std; 下面的全局变量 int num1, num2 = 0;。他们不再需要了。然后,通过删除(无效的)标准值赋值来修复 displaymenu 函数定义。在那之后,至少编译器应该接受你的代码,只是当你执行它时它在某些情况下不会真正起作用。