如何将指向对象的指针传递给函数? C ++

时间:2012-04-21 04:51:35

标签: c++ object reference

让我们说在main()中我从一个名为TheBuilder的类创建一个名为BOB的对象指针,我这样做

TheBuilder *BOB = new TheBuilder();

现在假设我有一个函数,我想将它传递给main中的helloWorld。如何将此BOB指针传递给TheBuilder对象?我如何调用它以及helloWorld()的参数列表是什么样的?

我希望能够修改BOB指向成员函数helloWorld内部的对象内部的数据。

我知道它可能有'*'或'&'但我不知道把它们放在哪里。

由于

5 个答案:

答案 0 :(得分:2)

int main()
{
    TheBuilder *BOB = new TheBuilder();
    helloWorld(BOB);
    if (BOB->canWeBuildIt)
        printf("yes we can!");
    delete BOB;
    return 0;
}

void helloWorld(TheBuilder *bob)
{
    bob->canWeBuildIt = true;
}

答案 1 :(得分:0)

void doSomething1(int x){ 
  //code 
} 

这个通过值传递变量,无论函数内部发生什么,原始变量都不会改变

void doSomething2(int *x){ 
  //code 
} 

这里将类型指针的变量传递给整数。因此,当访问该数字时,您应使用* x作为值,或使用x作为地址

void doSomething3(int &x){ 
  //code 
} 

这就像第一个,但无论函数内部发生什么,原始变量也会被改变

所以在你的情况下你会写

void helloWorld (TheBuilder* object){
    //Do stuff with BOB
}

void main (){
    TheBuilder *BOB = new TheBuilder();
    helloWorld (BOB);
}

答案 2 :(得分:0)

参数列表包含TheBuilder *参数。例如:

void helloWorld(TheBuilder *theBuilder) { ... }

并称之为:

helloWorld(BOB);

答案 3 :(得分:0)

class TheBuilder
{
    <class def>
}

void helloWorld (TheBuilder* obj)
{
    <do stuff to obj, which points at BOB>;
}

int main ()
{
    TheBuilder *BOB = new TheBuilder();
    helloWorld (BOB);
    return 0;
}

答案 4 :(得分:0)

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