如何访问此自动变量?

时间:2013-02-10 17:17:17

标签: c++ c++11 auto

我声明了一个自动类型的测试变量,但现在我不知道如何访问它。我知道如何在没有auto的情况下使这个程序工作,但在这里我想知道如何访问auto变量。

int main() {
auto test = {'1','S'};
std::cout<<test; //error no match for operator... i tried using *test or *test[0] but no solution.  
cin.get();
return 0;
}

编译日志:

Compiler: mingw
Executing  g++.exe...
g++.exe "C:\Users\Arpit\Desktop\delete.cpp" -o "C:\Users\Arpit\Desktop\delete.exe"   -std=c++11   
C:\Users\Arpit\Desktop\delete.cpp: In function 'int main()':
C:\Users\Arpit\Desktop\delete.cpp:5:12: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
In file included from c:\program files\codeblocks\mingw\bin\../lib/gcc/mingw32/4.7.1/include/c++/iostream:40:0,

                 from C:\Users\Arpit\Desktop\delete.cpp:1:
c:\program files\codeblocks\mingw\bin\../lib/gcc/mingw32/4.7.1/include/c++/ostream:600:5: error:   initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::initializer_list<char>]'

Execution terminated

如何打印test

2 个答案:

答案 0 :(得分:2)

您收到此错误,因为auto variable = { ... }声明了std::initializer_listoperator<<没有超载std::ostream。例如,您可以使用基于范围的内容来访问列表中的值。

int main()
{
    auto test = {'1','S'};
    for(const auto& elem: test)
        std::cout << elem << ' ';
    std::cout << std::endl;

    return 0;
}

答案 1 :(得分:2)

变量test的类型为std::initializer_list。您必须使用迭代器从中获取值,或者使用新的range-based for loop

auto test = { '1', 's' };
for (const auto& i : test)
    std::cout << i << '\n';