【发布时间】:2018-06-27 07:21:24
【问题描述】:
我这里有这段代码。
#include <iostream>
using namespace std;
template <typename T> inline T bigArry(const T data[5])
{
T level = data[0];
for(T item : data) // error C2143: syntax error : missing ',' before ':' (1st)
{ //error C2143: syntax error : missing ';' before '{' (3rd)
if(level<item){ level=item; }
}
return level;
}
int main()
{
int data[5]={//five variables}
cout << bigArry(data);//see reference to function template instantiation 'T bigArry<int>(const T [])' being compiled with [ T=int] (2nd)
return 0;
}
函数 bigArry() 返回 5 个元素的数组中的最大值。
问题是当我使用基于范围的循环时,它会给我代码中提到的错误。但是当我使用通常的 for 时,一切都会恢复正常。 我的意思是,对我来说语法看起来不错,我看不到问题所在。 我正在使用 Visual Studio 2010。
我想问的另一件事是关于内联函数。目前我正在阅读 C++ Primer Plus 第 6 版。我什么时候知道函数太大而无法内联?是否有代码应该多短的标准?或者,当我们“认为”没问题时,我们是否使用内联函数?
【问题讨论】:
-
你的第二个编译器错误不应该是
[ T=int ],而不是float吗? -
用
vector<T>怎么样? -
浮点数来自我声明的旧数组。
-
@RobertEagle:我想通了。但您可能需要对其进行编辑以避免一些可能的混淆。
-
Visual Studo 2010 不支持 c++11 ranged base for 循环?它只有一个较旧的自定义语法“for (T item in data) {}”