がメンバー関数の場合helloWorld
、オブジェクトポインタを渡す必要はありません。this
メンバー関数を呼び出したオブジェクトを指す、と呼ばれる暗黙のポインタがあります。
#include <iostream>
class TheBuilder
{
public:
void helloWorld();
std::string name_;
};
void TheBuilder::helloWorld()
{
//Here, you can use "this" to refer to the object on which
//"helloWorld" is invoked
std::cout << this->name_ << " says hi!\n";
//In fact, you can even omit the "this" and directly use member variables
//and member functions
std::cout << name << " says hi!\n";
}
int main()
{
TheBuilder alice; //constructs an object TheBuilder named alice
alice.name_ = "Alice";
TheBuilder bob; //constructs an object TheBuilder named bob
bob.name_ = "Bob";
alice.helloWorld(); //In helloWorld, "this" points to alice
//prints "Alice says hi!"
bob.helloWorld(); //In helloWorld, "this" points to bob
//prints "Bob says hi!"
}
実際、メンバー関数は、操作対象のオブジェクトに対応する暗黙的なパラメーターを持つフリー関数とほとんど同じです。次のコードを書くとき:
struct MyClass
{
int myMemberFunction() {...}
};
MyClass obj;
obj.myMemberFunction();
コンパイラによって生成されるコードは、次のものと同等です。
int myMemberFunction(MyClass * this) {...}
MyClass obj;
myMemberFunction(&obj);
しかし、あなたはそれについて気にする必要はありません。理解する必要があるのは、メンバー関数(オブジェクト指向用語のメソッド)がオブジェクトで呼び出され、呼び出されたオブジェクトを操作することです(たとえば、メンバー変数(フィールド)を変更できます)。メンバー関数では、名前を直接使用して現在のオブジェクトメンバーにアクセスするか、明示的にthis
ポインターを使用して現在のオブジェクトメンバーにアクセスできます。