2011-11-11 57 views
2

我完全不熟悉C++。愚蠢的語法錯誤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在的determineProfit參數提出profit下一個紅線,並說:

expected a ')' before identifier profit

我會感謝一些幫助。 謝謝!

+0

您正在編寫C#聲明。它是'int profit []'或'int * profit'。 –

+1

'N'始終爲1 ... – Neil

+0

如果您要編譯並鏈接,請記得添加一個int main(): –

回答

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.

+0

謝謝,這很好!^_^ –

+0

*還記得sizeof(array)將返回數組*中的字節數,實際上,在本例中爲'sizeof(profit)== sizeof(decay)',即sizeof(int *) '。數組已經衰減到指針,函數中的大小是未知的。 –

+0

是的你是對的,我在沒有函數參數的背景下想到它。 'int foo [10];的sizeof(FOO)== 40'。 – jli

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; 
+0

好的,這確實是另一個問題,但錯誤依然存在。 –

+1

@Lost_DM:不,它沒有。這是唯一的兩個語法問題。 –

2

此行是錯誤的:

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

更改成:

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

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

,並添加結束;

如果你這樣做,並添加一個主,當然:

int main() {} 

那麼你可以編譯代碼 - 我只是用G ++試了一下。

1

嘗試int determineProfit (int* profit, int* decay)因爲對於形式參數,數組和指針幾乎相同。

+0

「幾乎相同」但絕對不一樣。他使用'sizeof'和'sizeof(intptr)== 4',而'sizeof(intarray)== 4 * length'。 – jli

+0

@jli:在這種情況下實際上完全一樣。 –

+0

是的,我知道,我在你之前對我的評論中回答了這個問題。 – jli

0

方括號與變量名相關聯,而不是類型。第一行應是

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

arrays in C的指南可以是有啓發性,特別是關於數組參數通過。

0
int determineProfit (int[] profit int [] decay 

這裏是你的錯誤 - 上述說法是錯誤的;它應該是這樣的

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