[英]Passing argument by reference; does the function return type HAVE to be void?
我最近开始学习 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
类型函数完全正常工作(这是我评论过的方法),但我收到了大量错误或警告的第二个。 为什么会这样? 因为两者之间没有太大区别,我真的不明白怎么会有这么大的错误或警告。
我注意到该程序仍在运行,所以我猜这只是警告。
函数的参数与返回类型无关。
您收到的警告来自std::cout .... << doubleByReference(value)
,因为std::cout
需要一个值,但该函数不返回任何内容。
非法函数签名示例
void function(void& arg)
{
...
}
合法函数签名示例
下面的函数是 return void* 指针,它可以指向内存中的任何数据类型。 所以这里的返回类型不是 void 而是指向这里使用 void* 指定的任何类型的指针
void* function(void*& arg)
{
...
}
这里函数接受一个引用并返回对传递的参数的引用。 这只是例子
int& function(int& arg)
{
...
return arg;
}
同样在这里,我们也可以按值返回一个结构
struct mystruct {
int foo;
};
struct mystruct function(struct mystruct& arg)
{
return arg;
}
返回类型不必总是为空。 就像参数一样,你几乎可以返回任何东西。 您甚至可以返回指向函数、类、结构、其他原始类型等的指针。 但是你也必须遵循编程语言的规则。
引用传递的意义在于,该值可以在函数内部更改,并且在函数调用后的代码中保持更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.