その他の重要な機能

typedef

STLなどを使うと名前が長くなります。長い名前を何度も繰り返し入力するのは面倒ですし、プログラムが読みづらくなるときがあります。

こんなときにはtypedefが有用です。以下のように使います。

typedef int number;

これは、numberがintと同じ型を表すことを定義しています。

typedef char* text;

これは、textがchar*と同じ型を表すことを定義しています。

typedef std::vector<int> Integers;

これは、Integersがstd::vector<int>と同じ型を表すことを定義しています。

ここまでで、課題8までできるようになりました。残された課題に取り組んでください。

#include

#includeはプリプロセッサ命令の一つです。

The #include directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. (MSDNより)

#include命令は、指定されたファイルの内容があたかもそこに書かれているように扱うようにプリプロセッサに指示します。

例:

ファイルa.hの内容が

int test1()

{

return 1;

}

で、ファイルb.hの内容が

int test2()

{

return 2;

}

 で、ファイルc.cppの内容が

#include "a.h"

#include "b.h"

int main()

{

return test1() + test2();

}

のとき、ファイルc.ppの内容は以下と同様になります。

int test1()

{

return 1;

}

int test2()

{

return 2;

}

int main()

{

return test1() + test2();

}

""と<>の違い

#includeには

#include "file.h"という書き方と#include <file.h>という書き方があります。

この違いは指定したファイルの探し方の違いになります。

""を使うと、

This form instructs the preprocessor to look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file. The preprocessor then searches along the path specified by the /I compiler option, then along paths specified by the INCLUDE environment variable.(MSDNより)

まず、その#include文のあるファイル(仮にfile1.hとします。)と同じディレクトリ(=フォルダ)を探します。次に、file1.hをインクルードしたファイルがあるディレクトリを探します。複数のファイルがfile1.hをインクルードしているときはすべてのディレクトリが検索の対象になります。次に、コンパイラオプションの/Iで指定されているディレクトリが検索されます。最後に環境変数INCLUDEに指定されているディレクトリが検索されます。

<>を使うと、

This form instructs the preprocessor to search for include files first along the path specified by the /I compiler option, then, when compiling from the command line, along the path specified by the INCLUDE environment variable.(MSDNより)

最初に、コンパイラオプションの/Iで指定されているディレクトリが検索されます。次に、もし、コマンドラインでコンパイラが実行された場合は環境変数INCLUDEに指定されているディレクトリが検索されます。

通常自分で作ったファイルは#include ""の形式を、ライブラリなどは#include<>の形式を使います。

 

以下は準備中です。

名前空間(namespace)

プリプロセッサ命令(マクロ)

#define

#define文の基本は第一引数を第二引数で置き換えることです。

例:

#define MAX 100

int x = MAX;

#define MAX 100

int x = 100;

と同等になります。

引数を使ってマクロの定義もできます。

例:

#include <iostream>

#define add(x, y) x+y

int main()

{

std::cout << add(1,2) << std::endl;

return 1;

}

上の例では、add(1,2)が1+2に置き換わります。

第二引数のない使い方もよく見られます。

例:

#define TESTA_H

これは、同一のファイルが同じファイルを2度以上インクルードしないために使うテクニックです。

#ifndefと合わせて使います。

例:

ファイルtesta.hの内容が

#ifndef TESTA_H

#define TESTA_H

int test1()

{

return 1;

}

#endif

で、ファイルtestb.cppの内容が

#include "testa.h"

#include "testa.h"

int main()

{

return test1();

}

としてもエラーになりません。

#ifndef は、第一引数が既に#defineで定義されていないときその内側(#ifndefと#endifの間)の記述を有効にする命令です。#ifdefは#ifndefの逆の動作をします。