作者genius091612 (真愛飛翔)
看板C_and_CPP
標題[問題] include Student.h 與 class Student; 的差別
時間Mon Nov 30 22:05:36 2009
前幾天,我們老師出了一題作業,一些將 .cpp 和 .h 分開的簡單練習。
.h 即是宣告, .cpp 自然是實做內容了。
就是幾個 class 在那 include 來 include 去這樣。
先說一下,我的 compiler 是 gcc。
然後我遇到了個問題,話不多說,post code 先。
#ifndef _DEPARTMENT_H_
#define _DEPARTMENT_H_
#include <string>
#include <vector>
#include "CourseOffering.h"
class Student;
using namespace std;
class Department {
public:
Department(string);
string getName();
void addStudent(Student *);
Student* getStudent();
int numberOfStudents();
int numberOfCourses();
void DataOffering(CourseOffering *);
private:
string _name;
vector<Student *> _students;
vector<CourseOffering *> _offer;;
};
#endif
這是其中一個 .h 檔。我的問題即是黃色部份。
到底為什麼要寫 class Student; 呢?寫 include "Student.h" 不行嗎?
Student.h 裡確確實實只有 Student 的 class 宣告。
照理來說這兩種寫法意思應該一樣啊,但要是改成 include "Student.h"就一堆錯誤...
請問到底是差在哪呢?還有什麼情況要寫這種,什麼時候甫可寫 include "Student.h"?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.124.135.189
1F:推 LPH66:你的 Student 有用到 Department 嗎? 11/30 22:08
2F:→ genius091612:有的,public裡有作為member function return type的 11/30 22:17
3F:→ genius091612:也有作為引數傳入的。private裡也宣告了一指標。 11/30 22:18
4F:→ james732:建議列出「一堆錯誤」 11/30 22:49
5F:推 legnaleurc:你可以重覆宣告, 但是你不能重覆定義 11/30 23:01
6F:→ tinlans:這樣寫可以減輕 header file 之間的相依關係,等將來程式 11/30 23:04
7F:→ tinlans:寫大了你就知道,沒處理好這個的話,.h 檔改一行,要重新 11/30 23:04
8F:→ tinlans:編譯上百個檔案,有處理好的話搞不好只有三四個檔要重編。 11/30 23:05
9F:→ tinlans:前者 20 分鐘,後者大概 30 秒。 11/30 23:05
10F:→ tinlans:簡單來說,你有 10 個 .cpp 只有 include Department.h, 11/30 23:10
11F:→ tinlans:而沒有 include Student.h,那麼你修改 Student.h,這 10 11/30 23:10
12F:→ tinlans:個 .cpp 就不用重編,但是你一讓 Department.h 去 11/30 23:10
13F:→ tinlans:include 了 Student.h,那你只要修改 Student.h,除了直接 11/30 23:11
14F:→ tinlans:include Student.h 的 .cpp 檔外,你那 10 個 .cpp 也要全 11/30 23:11
15F:→ tinlans:部重編。 11/30 23:11