通过引用传递参数;函数返回类型HAVE是否为void?

问题描述 投票:0回答:3

我最近开始学习C ++,现在我正在学习将参数传递给函数。知道有两种方法可以这样做,因此我编写了一个简单的代码,将用户给出的数字加倍。

我的第一个问题是,通过引用将参数传递给函数时,该函数必须为void类型还是也可以为int

我问这个问题,因为我看到的大多数示例都在使用void。

第二个问题是我的代码,


    #include <iostream>


    //using std::cout;
    //using std::cin;
    //using std::endl;


    using namespace std;


    int doubleByValue(int value){       //this is the function which takes the argumrnt passed down by main as a Value
        int Doubled;
        Doubled = value * value;

        return Doubled;
    }

    /*
    int doubleByReference(int &value){      //This is the function which takes the argument passed from main as a Reference
        value = value * value;

        return value;
    }
    */

    void doubleByReference(int &value){     //This is the function which takes the argument passed from main as a Reference
        value = value * value;

    }


    int main(){
        cout << "In this program we would be doubling the values entered by the user" << endl;
        cout << "using the two methods of passing arguments, through value and by reference." << endl;


        int Number = 0;
        cout << "Please enter a Number: ";
        cin >> Number;


        cout << endl << "Number doubled after passed by Value: " << doubleByValue(Number) << endl;
        cout << endl << "Number doubled after passed by Reference: " << doubleByReference(Number) << endl;

        return 0;
    }

我的最佳方法,即通过值方法传递参数的方法完全正常。

但是,我使用了两种方法来通过引用传递参数,通过该方法,类型int函数可以完全正常工作(这是我已经评论过的函数),但是第二种方法却出现了大量错误或警告一。为什么会这样呢?因为两者之间没有太大区别,我真的不明白为什么会有这么大的错误或警告。

[我注意到程序仍在运行,所以我猜它只是警告。

c++ function reference return pass-by-reference
3个回答
3
投票

函数的参数和返回类型无关。

您收到的警告来自std::cout .... << doubleByReference(value),因为std::cout需要一个值,但该函数不返回任何值。


0
投票

返回类型不必总是为空。就像参数一样,您几乎可以返回任何内容。您甚至可以返回指向函数,类,结构,其他原始类型等的指针。但您还必须遵循编程语言的规则。


-1
投票

FAFSHOCK,您的参数可以是任何类型,只要它符合编译器规范

© www.soinside.com 2019 - 2024. All rights reserved.