开发者

C++ instantiating a class within a method, then altering member variables from a different method?

Say I have a method, and within that method it instantiates a Person class:

void methodA()
{
    Person personObject;
}

How would I access that o开发者_C百科bject's methods from within another method? I.e. something like:

void methodB()
{
    personObject.someMethod();
}

I realise it's a painfully nooby question :P


Pass a reference to the other function.

void methodB(Person &personObject)
{
    personObject.someMethod();
}

void methodA()
{
    Person personObject;
    methodB(personObject);
}


You can't. The first Person object is a local object and disappears once outside the scope of the function. You'd need to make it part of the class for other methods to view it.


You'll need to make personObject a member of the class. Also, if you must create personObject in methodA, rather than having it initialized in the constructor, then you'll need to dynamically create the object with new.

class MyClass
{
public:
    MyClass()
        : personObject(0)
    {
    }
    ~MyClass() 
    {
        delete personObject;
    }
    void methodA()
    {
        personObject = new Person();
    }
    void methodB()
    {
        personObject->someMethod();
    }
private:
    Person* personObject;
};


Probably you want the personObject to be a member variable of your class:

class SomeClass {
   Person personObject;
public:
   void methodA();
   void methodB();
};

void SomeClass::methodA() {
    personObject = Person(123);
}

void SomeClass::methodB() {
    personObject.someMethod();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜