如果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
指针。