私は「AcceleratedC++」という本で母国語を学ぶ学生プログラマーです。作者がヘッダーファイルと関数を含むソースファイルについて説明しているところです。この本で説明されている演習では、作成者は関数の定義を含むヘッダーファイルを持っていますが、ソースファイルにも関数の定義があるため冗長に見えます。この場合、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は、ソースにすでに定義が含まれている場合でも、median関数のソースファイルにコピーされますvector<double> vec
。この本では、無害で実際には良いアイデアであると説明しています。しかし、私はそのような冗長性の理由をよりよく理解したいだけです。どんな説明でも素晴らしいでしょう!