我是一名學生程序員,學習我的第一本語言「加速C++」。我處於作者正在解釋包含函數的頭文件和源文件的時候。在本書提供的解釋中,作者具有包含函數定義的頭文件,但由於源文件也具有函數的定義,因此似乎是多餘的。在編程C++時,這種情況下頭文件的要點是什麼?C頭文件和源文件
示例:頭文件。
#ifndef MEDIAN_H
#define MEDIAN_H
#include <vector>
double median(std::vector<double>);
#endif // MEDIAN_H
然後包含函數的源文件,以確定等級的中位數:
// source file for the `median' function
#include <algorithm> // to get the declaration of `sort'
#include <stdexcept> // to get the declaration of `domain_error'
#include <vector> // to get the declaration of `vector'
using std::domain_error; using std::sort; using std::vector;
#include "median.h"
// compute the median of a `vector<double>'
// note that calling this function copies the entire argument `vector'
double median(vector<double> vec)
{
#ifdef _MSC_VER
typedef std::vector<double>::size_type vec_sz;
#else
typedef vector<double>::size_type vec_sz;
#endif
vec_sz size = vec.size();
if (size == 0)
throw domain_error("median of an empty vector");
sort(vec.begin(), vec.end());
vec_sz mid = size/2;
return size % 2 == 0 ? (vec[mid] + vec[mid-1])/2 : vec[mid];
}
的median.h被複制到即使源已經定義vector<double> vec
本書中位數函數源文件解釋爲無害,實際上是一個好主意。但我只想更好地理解這種冗餘的原因。任何解釋都會很棒!
頭部通常具有有限的**聲明**。實施有完整的定義。 – chris 2013-03-04 03:49:28
當您開始使用具有多個文件的項目時,您會看到需要。 – jman 2013-03-04 03:50:40
http://stackoverflow.com/questions/1305947/why-does-c-need-a-separate-header-file – jman 2013-03-04 03:52:25