简体   繁体   English

如何在 C++ 中使用关键字“auto”声明和使用变量?

[英]How to declare and use a variable using key word "auto" in C++?

As the title, how to I could declare a variable using key word "auto" in C++ I've been tried, but failed正如标题,我已经尝试过如何在 C++ 中使用关键字“auto”声明一个变量,但失败了

#include <iostream>
 using namespace std;
 int main(int argc, char const *argv[])
 {
      auto v;
      cin >> v;
      cout << v << endl;
      return 0;
  }

You can use it when getting results from a function if you don't know the exact type it returns.如果您不知道函数返回的确切类型,则可以在从函数获取结果时使用它。

auto test = someFunc();
cout << a;

For example, of what type is the result of std::vector<int>().begin() ?例如, std::vector<int>().begin()的结果是什么类型? No need to worry about this:无需担心:

std::vector<int> myvector = {1, 2, 3};

for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
std::cout << ' ' << *it;

You can simplify it to the following:您可以将其简化为以下内容:

for (auto it = myvector.begin() ; it != myvector.end(); ++it)
std::cout << ' ' << *it;

As you can see, you don't really need to know the type of it , now it's your compiler's job.如您所见,您真的不需要知道it的类型,现在这是您的编译器的工作。

the reason is that auto doesnt behave in the same way as php and javascript's var do.原因是 auto 的行为方式与 php 和 javascript 的 var 不同。 auto is simply "make it the same type as the data which i am assigning to it". auto 只是“使其与我分配给它的数据的类型相同”。 It's not a data type on its own.它本身不是一种数据类型。

As you can see, you are not assigning any data when you create the variable in your example, so the compiler cannot tell what the type is supposed to be.如您所见,在示例中创建变量时没有分配任何数据,因此编译器无法判断类型应该是什么。

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

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