我是C++的新手.
在一个多小时内抨击这个错误.可能有经验的人可以通过它看到.
以下代码给出了错误:
class TimeTravellingCellar {
private:
public:
int determineProfit (int [] profit, int [] decay) {
int N = sizeof(profit)/sizeof(decay);
int max = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
if (profit [i] - decay [j] > max)
max = profit [i] - decay [j];
}
}
return max;
}
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio Express profit在参数中放置一条红线,determineProfit并说:
expected a ')' before identifier profit.
我会感激一些帮助.谢谢!
Ed *_* S. 12
您声明您的数组就好像这是c#.它应该是
int profit[]
Run Code Online (Sandbox Code Playgroud)
要么
int *profit
Run Code Online (Sandbox Code Playgroud)
你接下来会打这个.你需要用分号终止你的课程.
class Foo {
}; <----
Run Code Online (Sandbox Code Playgroud)
你遇到的下一个问题是合乎逻辑的,而不是语法问题.这不符合你的想法:
int N = sizeof(profit)/sizeof(decay);
Run Code Online (Sandbox Code Playgroud)
您正在使用sizeof两个指针,而不是数组的大小.你实际上有:
int N = 4/4 /* assumes sizeof int == 4 */
Run Code Online (Sandbox Code Playgroud)
你需要将你的大小传递给函数(或者更好的是;停止使用数组并使用vector<T>.)
当你将"数组"作为函数的参数时,它实际上会衰减到指向数组类型的指针(一个数组本身不能传递给函数).所以它遵循:
void Foo( int array[] ) {
size_t arrSize = sizeof(array);
// arrSize == 4 for a 32-bit system, i.e., sizeof(int*)
int a[100];
size_t actualSizeInBytes = sizeof(a);
// actualSizeInBytes == 400, i.e., 4 * 100 as an int occupies 4 bytes
}
Run Code Online (Sandbox Code Playgroud)
接下来,此行会导致始终跳过第一次迭代.不确定这是否是故意的:
if (i == j) continue;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
367 次 |
| 最近记录: |