作者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