为什么我们必须在箭头符号(->)之后再次指定数据类型 [英] Why we have to specify data type again after the arrow symbol ( -> )

查看:58
本文介绍了为什么我们必须在箭头符号(->)之后再次指定数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

auto 可以推断出返回类型,那么为什么我们需要用后退箭头符号(->)来推断返回类型

auto can deduce the return type then why do we need trailing arrow symbol (->) to deduce the return type

#include <iostream>   
auto add (int i, int j)->int
{
    return i+j;
}
int main()
{
    int x=10,y=20;
    std::cout<<add(x,y);
 }


推荐答案

在C ++ 11中,函数没有返回类型推导。 auto 不是此处要推断出的占位符类型。您可能会说它的含义已超载。

In C++11, there is no return type deduction for functions. auto is not a placeholder type to be deduced here. You could say its meaning is overloaded.

对于函数, auto 只是意味着将返回类型指定为尾随返回类型。您不能忽略结尾的返回,否则您的程序将格式不正确。

For functions, auto simply means the return type will be specified as a trailing return type. You cannot omit the trailing return, or your program will be ill-formed.

此功能已添加到语言中,以允许返回类型说明取决于函数参数,或成员的封闭课程。到达尾随的返回类型时,它们被视为可见。

This feature was added to the language to allow return type specification to depend on the functions parameters, or enclosing class for members. Those are considered "seen" by the time the trailing return type is reached.

例如,在此类中:

namespace baz {
    struct foo {
        enum bar {SOMETHING};
        bar func();
    };
}

如果我们在C ++ 03中不实现该成员函数,会看起来像这样:

If we implement that member function out of line in C++03, it would have to look like this:

baz::foo::bar baz::foo::func() {
    return SOMETHING;
}

我们必须为返回类型指定完全限定名称。很快就会变得不可读。但是带有尾随的返回类型:

We must specify the fully qualified name for the return type. Which can quickly become unreadable. But with trailing return types:

auto baz::foo::func() -> bar {
    return SOMETHING;
}

已经看到完整的封闭名称空间,并且 bar 可以使用无限制的ID来指定。

The full enclosing namespace is already seen, and bar can be specified using an unqualified id.

这篇关于为什么我们必须在箭头符号(-&gt;)之后再次指定数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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