0

我声明了一个自动类型的测试变量,但现在我不知道如何访问它。我知道如何使这个程序在没有的情况下工作,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

4

2 回答 2

2

你得到这个错误,因为auto variable = { ... }声明了一个std::initializer_list,它没有重载operator<<for std::ostream。例如,您可以使用基于范围的 for 来访问列表中的值。

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

    return 0;
}
于 2013-02-10T17:25:56.077 回答
2

变量test的类型为std::initializer_list。您必须使用迭代器从中获取值,或者使用新的基于范围的 for 循环

auto test = { '1', 's' };
for (const auto& i : test)
    std::cout << i << '\n';
于 2013-02-10T17:26:17.770 回答