参见英文答案 >
Range based for-loop on array passed to non-main function2个
这些天我自己学习C并且我有一些问题需要理解为什么这段代码不使用#g -std = c 11 source.cpp进行编译.实际上我使用哪个特定标准并不重要,它只是不编译.
这些天我自己学习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; }
错误消息:
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 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’
解决方法
它不编译的原因是在C中,一个函数参数如char array []被调整为char * array.你的功能真的很像
int print_a(char* array) { .... }
并且基于范围的循环不能处理指针.
一种解决方案是通过引用传递数组. C不允许您按值传递普通数组.例如,这将接受5个字符的数组:
int print_a(const char (& array)[5]) { for(char c : array) cout << c; cout << endl; return 42; }
为了将其推广到不同大小的数组,您可以使用模板:
template <std::size_t N> int print_a(const char (& array)[N]) { for(char c : array) cout << c; cout << endl; return 42; }
当然,有更简单的方法来打印以null结尾的字符串:
char hello[] {"Hello!"}; cout << hello << endl;
并且有标准库类型可以使传递字符串或char缓冲区对象更容易.例如,std :: string,std :: vector< char> ;,std :: array< char,N> (其中N是编译时常量.)