愚蠢的语法错误c ++

时间:2011-11-11 20:53:39

标签: c++ syntax

我对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; 
  } 
}

Visual Studio Express在profit的{​​{1}}参数中放置一条红线,并说:

determineProfit

我会感激一些帮助。 谢谢!

7 个答案:

答案 0 :(得分:12)

您声明您的数组就好像这是c#。它应该是

int profit[]

或者

int *profit

接下来你会打这个。你需要用分号终止你的课程。

class Foo { 

};  <----

你拥有的下一个问题是合乎逻辑的,而不是语法问题。这不符合你的想法:

int N = sizeof(profit)/sizeof(decay); 

你正在使用sizeof两个指针,而不是数组的大小。你实际上有:

int N = 4/4  /* assumes sizeof int == 4 */

你需要将你的大小传递给函数(或者更好的是;停止使用数组并使用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
}

接下来,此行会导致始终跳过第一次迭代。不确定这是否是故意的:

if (i == j) continue; 

答案 1 :(得分:3)

你没有在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; 
  } 
};

编辑:还记得sizeof(指针)将返回指针类型的字节数,而不是数组中的元素数。因此,如果您有一个int数组,sizeof(array) == sizeof(int)。您的N值始终等于1.

答案 2 :(得分:2)

这一行错了:

 int determineProfit (int [] profit, int [] decay) { 

将其更改为:

int determineProfit (int profit[], int decay[]) { 

int determineProfit (int* profit, int* decay) { 

并添加结束;

如果你这样做并添加一个主要的,当然:

int main() {}

然后你可以编译你的代码 - 我只是用g ++尝试过它。

答案 3 :(得分:1)

尝试int determineProfit (int* profit, int* decay),因为对于形式参数,数组和指针几乎是相似的。

答案 4 :(得分:0)

括号与变量名称相关联,而不是与类型相关联。第一行应该是

int determineProfit (int profit[], int decay[]) { 

答案 5 :(得分:0)

关于arrays in C的教程可能很有启发性,特别是关于数组参数的传递。

答案 6 :(得分:0)

int determineProfit (int[] profit int [] decay 

这是你的错误 - 上面的陈述是错误的;它应该是这样的

int determineProfit (int profit[], int decay[])