简体   繁体   English

bool 类型的函数接收参数(引用)并可能在 C++ 中返回它?

[英]Function of type bool receiving parameter (reference) and possibly return it in C++?

I have a homework task in my university where I should make a function of type bool(double &var) which takes a reference to the variable as a parameter.我在我的大学有一个家庭作业任务,我应该制作一个类型为bool(double &var)的函数,它将对变量的引用作为参数。 Then the function performs some calculations and should calculate the result in a new seperate variable, but at the same time return it in the var variable (the parameter of the function).然后函数执行一些计算,应该在一个新的单独变量中计算结果,但同时在var变量(函数的参数)中返回它。 I would like to ask how can this be accomplished?请问这个怎么实现? Below is a simple example of the problem:下面是一个简单的问题示例:

#include <iostream>
using namespace std;
double rez;
bool func(double &var){
//var = 5;
if(var>3){
    rez = var;
    return var;
}
else{
    return false;
}
}
int main(){

}

When you pass-by-value.当您按值传递时。 like bool func(double var) , what happens is that you get a local var , which will be gone if you leave scope.bool func(double var) ,发生的情况是你得到一个局部var ,如果你离开作用域,它就会消失。 Imagine something like this: A function想象一下这样的事情:一个函数

bool func(double var) {
     double res = var * 2;
     return true;
}

called like this:像这样调用:

double someVar = 5;
bool success = func(someVar);

You could calculate with var all you want, when returning from func the local copy var will be gone and you are left with someVar == 5 .你可以用你想要的var计算,当从func返回时,本地副本var将消失,你只剩下someVar == 5

Now, when you pass per reference (ie bool func(double &var) ) everything you do with the passed var will be done to the original one.现在,当您通过每个引用(即bool func(double &var) )时,您对传递的var所做的一切都将对原始引用进行。 That means when returning from func you would be left with someVar == 10 .这意味着当从func返回时,你会留下someVar == 10 success would be true in either way.无论哪种方式, success都是正确的。

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM