如果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
指针。
考虑一个C++教程。 – 2012-04-21 04:54:32
^aha ..来吧..让我们来帮助这个家伙。我曾经在他的位置上,并且确实必须读一本书来弄清楚。但是,直到我在一个使用stackoverflow的人问起时,它仍然感到困惑!谁知道今天他可能终于知道什么时候给你使用什么,如果我们给他一个短暂的贷款手!毕竟他只是要求一个快速的解释,所以他可以做出正确的决定,使用哪一个:D – Pavan 2012-04-21 04:57:55
这是一个太基本的问题。我建议你阅读关于C++的简短教程,你会发现所有的答案,最有可能的是第二或第三段。 – 2012-04-21 04:58:09