"クラス内"(I)メソッドは、 "クラス外"(O)メソッドと同じです。
ただし、クラスが1つのファイル(.cppファイル内)でのみ使用される場合は、(I)を使用できます。 (O)は、ヘッダファイル内にあるときに使用されます。 cppファイルは常にコンパイルされます。ヘッダーファイルは#include "header.h"を使用するとコンパイルされます。
ヘッダーファイルで(I)を使用すると、関数fun1は#include "header.h"をインクルードするたびに宣言されます。これにより、同じ関数を複数回宣言することができます。これはコンパイルするのが難しく、エラーにつながることさえあります。正しい使用方法について
例:
ファイル1: "Clazz.h"
//This file sets up the class with a prototype body.
class Clazz
{
public:
void Fun1();//This is a Fun1 Prototype.
};
ファイル2: "Clazz.cpp"
#include "Clazz.h"
//this file gives Fun1() (prototyped in the header) a body once.
void Clazz::Fun1()
{
//Do stuff...
}
FILE3: "UseClazz.cpp"
#include "Clazz.h"
//This file uses Fun1() but does not care where Fun1 was given a body.
class MyClazz;
MyClazz.Fun1();//This does Fun1, as prototyped in the header.
File4: "AlsoUseClazz.cpp"
#include "Clazz.h"
//This file uses Fun1() but does not care where Fun1 was given a body.
class MyClazz2;
MyClazz2.Fun1();//This does Fun1, as prototyped in the header.
File5: "DoNotUseClazzHeader.cpp"
//here we do not include Clazz.h. So this is another scope.
class Clazz
{
public:
void Fun1()
{
//Do something else...
}
};
class MyClazz; //this is a totally different thing.
MyClazz.Fun1(); //this does something else.
おそらく初心者のC++の本が注文されている可能性がありますか? –
@Downvotersなぜですか?私の質問に何が間違っていますか? – JohnJohnGa
ここには実際に3つのオプションがあります。 2番目の例では、ヘッダファイルに関数定義を含めることができます(ただし、まだインライン化されていません)。または、別の '.cpp'ファイルに定義されています。 –