如果一个函数返回一个int,可以分配一个int呢? [英] If a functions return an int, can an int be assigned to it?

查看:177
本文介绍了如果一个函数返回一个int,可以分配一个int呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果函数返回一个int,可以通过int值赋值吗?我不觉得给一个函数赋值太有意义了。

If a function returns an int, can it be assigned by an int value? I don't see it makes too much sense to assign a value to a function.

int f() {}

f() = 1;


$ b $ p

我注意到,如果函数返回一个int的引用,它只限于int吗?其他类型怎么样?或任何其他规则?

I noticed that, if the function returns a reference to an int, it is ok. Is it restricted only to int? how about other types? or any other rules?

int& f() {}

f() = 1;


推荐答案

第一个函数返回一个整数by-是 r值。通常不能将r值分配给r值。第二个f()返回一个整数的引用,这是一个l值 - 所以你可以赋值给它。

The first function returns an integer by-value, which is an r-value. You can't assign to an r-value in general. The second f() returns a reference to an integer, which is a l-value - so you can assign to it.

int a = 4, b = 5;

int& f() {return a;}

...
f() = 6;
// a is 6 now

注意:函数,你只需分配给它的返回值。
注意以下几点:

Note: you don't assign a value to the function, you just assign to its return value. Be careful with the following:

int& f() { int a = 4; return a; }

您正在返回对临时的引用,该函数在函数返回后不再有效。访问引用将调用未定义的行为。

You're returning a reference to a temporary, which is no longer valid after the function returns. Accessing the reference invokes undefined behaviour.

这篇关于如果一个函数返回一个int,可以分配一个int呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆