2013-02-20 44 views
0

C++新手。只是做一個簡單的結構/數組程序。爲什麼我無法傳遞像我打算在這裏的一系列結構?這個結構被定義,所以爲什麼函數認爲它不是?

int NumGrads(); 

int main() 
{ 
     struct Student { 
      int id; 
      bool isGrad; 
     }; 

    const size_t size = 2; 
    Student s1, s2; 
    Student students[size] = { { 123, true }, 
          { 124, false } }; 

    NumGrads(students, size); 

    std::cin.get(); 
    return 0; 
} 

int NumGrads(Student Stu[], size_t size){ 

} 

我明白,它必須是與路過的參考值或值,但肯定如果我在main()定義了它,我不應該與NumGrads的參數得到一個錯誤?

回答

6

Studentmain()中定義。 定義它的主要外部,使得它在相同的範圍內NumGrads

struct Student 
{ 
     int id; 
     bool isGrad; 
}; 

int main() 
{ 
     ... 
} 
12

你的結構定義main,和你的NumGrads功能之外main定義

這意味着你的結構被定義在你的函數可以看到它的範圍之外。

將您的結構的定義移動到main上方並解決您的問題。

6

結構定義是main的本地。 main以外的任何內容都不能看到,包括您的NumGrads定義。在函數內部定義一個結構體定義並不是一件很常見的事情 - 通常你會在命名空間範圍內使用它。

另外您的NumGrads聲明不符合定義的參數類型。

// Define Student at namespace scope 
struct Student { 
    int id; 
    bool isGrad; 
}; 

int NumGrads(Student[], size_t); // The argument types are now correct 

int main() 
{ 
    // ... 
} 

int NumGrads(Student Stu[], size_t size){ 

} 
+0

+1 NumGrads'聲明補充修正 – Peopleware 2013-02-20 15:33:27

3

struct Student聲明的主裏面,所以int NumGrads無法看到它。此外,該函數未在main中稱之爲未聲明的位置。在這一點上,唯一可用的聲明是int NumGrads(),這是一個不同的功能。

相關問題