为什么我需要明确写出“auto"关键字? [英] Why do I need to explicitly write the 'auto' keyword?

查看:32
本文介绍了为什么我需要明确写出“auto"关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 C++98 转向 C++11,并且已经熟悉 auto 关键字.我想知道如果编译器能够自动推断类型,为什么我们需要显式声明 auto.我知道 C++ 是一种强类型语言,这是一条规则,但是如果不显式声明变量 auto 就不可能达到相同的结果吗?

I am moving towards C++11 from C++98 and have become familiar with the auto keyword. I was wondering why we need to explicitly declare auto if the compiler is able to automatically deduce the type. I know C++ is a strongly typed language and this is a rule but was it not possible to achieve the same outcome without explicitly declaring a variable auto?

推荐答案

删除显式 auto 会破坏语言:

Dropping the explicit auto would break the language:

例如

int main()
{
    int n;
    {
        auto n = 0; // this shadows the outer n.
    }
}

您可以看到,删除 auto 不会遮蔽外部 n.

where you can see that dropping the auto would not shadow the outer n.

这篇关于为什么我需要明确写出“auto"关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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