返回类型在c ++ [英] return type in c++

查看:156
本文介绍了返回类型在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>

int & fun();
int main()
{
    int p = fun();
    std::cout << p;
    return 0;
}

int & fun()
{
    int a=10;
    return a;
}

为什么这个程序在第6行不给出错误从int *到int,因为它发生在我们这样做的情况下?

Why is this program not giving error at line no.6 as "invalid conversion from int* to int", as it happens in case we do like this?

 int x = 9;
 int a = &x;


推荐答案

int& c $ c>是一个类型;它表示引用 int

& x 是一个表达式;它的意思是取地址 x 。一元& 运算符是地址运算符。它需要它的参数的地址。如果 x int ,则& x 是指向 int (即 int * )的指针。

&x is an expression; it means "take the address of x." The unary & operator is the address operator. It takes the address of its argument. If x is an int, then the type of &x is "a pointer to int" (that is, int*).

int& int * 是不同类型。引用和指针在许多方面是相同的;即,它们都指的是对象,但它们在使用方式上有很大的不同。一方面,引用隐式引用一个对象,并且不需要间接访问被引用的对象。需要显式间接(使用 * - > )来获取指针引用的对象。

int& and int* are different types. References and pointers are the same in many respects; namely, they both refer to objects, but they are quite different in how they are used. For one thing, a reference implicitly refers to an object and no indirection is needed to get to the referenced object. Explicit indirection (using * or ->) is needed to get the object referenced by a pointer.

& 的这两种使用完全不同。它们不是唯一的用途:例如,还有执行按位和操作的二进制& 运算符。

These two uses of the & are completely different. They aren't the only uses either: for example, there is also the binary & operator that performs the bitwise and operation.

请注意,您的函数 fun 不正确,因为您返回对局部变量的引用。一旦函数返回, a 被销毁并不再存在,所以你永远不能使用从函数返回的引用。如果您使用它,例如。通过将 fun()的结果分配给 p ,行为是未定义的。

Note also that your function fun is incorrect because you return a reference to a local variable. Once the function returns, a is destroyed and ceases to exist so you can never use the reference that is returned from the function. If you do use it, e.g. by assigning the result of fun() to p as you do, the behavior is undefined.

从函数返回引用时,必须确定引用引用的对象将在函数返回后存在。

When returning a reference from a function you must be certain that the object to which the reference refers will exist after the function returns.

这篇关于返回类型在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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