Dav*_*ycc 6 c++ for-loop c++11
我这些天自己学习C++并且我有一些问题需要理解为什么这段代码不能编译使用#g++ -std=c++11 source.cpp.实际上我使用哪个特定标准并不重要,它只是不编译.
#include <iostream>
#include <string>
using namespace std;
int print_a(char array[])
{
for(char c : array)
cout << c;
cout << endl;
return 0;
}
int main(void)
{
char hello[] {"Hello!"};
print_a(hello);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误消息:
debian@debian:~/Documents$ g++ -std=c++11 source.cpp
source.cpp: In function ‘int print_a(char*)’:
source.cpp:6:15: error: ‘begin’ was not declared in this scope
for(char c : array)
^
source.cpp:6:15: note: suggested alternatives:
In file included from /usr/include/c++/4.9/bits/basic_string.h:42:0,
from /usr/include/c++/4.9/string:52,
from /usr/include/c++/4.9/bits/locale_classes.h:40,
from /usr/include/c++/4.9/bits/ios_base.h:41,
from /usr/include/c++/4.9/ios:42,
from /usr/include/c++/4.9/ostream:38,
from /usr/include/c++/4.9/iostream:39,
from source.cpp:1:
/usr/include/c++/4.9/initializer_list:89:5: note: ‘std::begin’
begin(initializer_list<_Tp> __ils) noexcept
^
/usr/include/c++/4.9/initializer_list:89:5: note: ‘std::begin’
source.cpp:6:15: error: ‘end’ was not declared in this scope
for(char c : array)
^
source.cpp:6:15: note: suggested alternatives:
In file included from /usr/include/c++/4.9/bits/basic_string.h:42:0,
from /usr/include/c++/4.9/string:52,
from /usr/include/c++/4.9/bits/locale_classes.h:40,
from /usr/include/c++/4.9/bits/ios_base.h:41,
from /usr/include/c++/4.9/ios:42,
from /usr/include/c++/4.9/ostream:38,
from /usr/include/c++/4.9/iostream:39,
from source.cpp:1:
/usr/include/c++/4.9/initializer_list:99:5: note: ‘std::end’
end(initializer_list<_Tp> __ils) noexcept
^
/usr/include/c++/4.9/initializer_list:99:5: note: ‘std::end’
Run Code Online (Sandbox Code Playgroud)
它不编译的原因是,在C++中的功能参数,例如char array[]被调整到char* array.你的功能真的很像
int print_a(char* array)
{
....
}
Run Code Online (Sandbox Code Playgroud)
并且基于范围的循环不能处理指针.
一种解决方案是通过引用传递数组.C++不允许您按值传递普通数组.例如,这将接受5 char秒的数组:
int print_a(const char (& array)[5])
{
for(char c : array) cout << c;
cout << endl;
return 42;
}
Run Code Online (Sandbox Code Playgroud)
为了将其推广到不同大小的数组,您可以使用模板:
template <std::size_t N>
int print_a(const char (& array)[N])
{
for(char c : array) cout << c;
cout << endl;
return 42;
}
Run Code Online (Sandbox Code Playgroud)
当然,有更简单的方法来打印以null结尾的字符串:
char hello[] {"Hello!"};
cout << hello << endl;
Run Code Online (Sandbox Code Playgroud)
并且有标准库类型可以使传递字符串或char缓冲区对象更容易.例如,std::string,std::vector<char>,std::array<char, N>(其中,N是编译时间常数.)