Pergunta

Let's say I have a class with an object for a member:

class Class1
{
    private:
        Class2 anObject;
}

And an integer variable and an accessor in the other class:

class Class2
{
    private:
        int aVariable;
    public:
        int getAVariable()
        {
             return aVariable;
        }
}

What's the best way to access aVariable from main?

For example, if anObject is declared public rather than private I can do this in main:

int main()
{
    Class1 Class1Object;
    cout << Class1Object.anObject.getAVariable() << '\n';
}

But how would I do this if anObject is kept private?

Foi útil?

Solução

get a public getter for the object you want in class 1.

public:
    Class2 getObject()
    {
         return anObject;
    }

and then you can do

 int main()

{
Class1 Class1Object;
cout << Class1Object.getObject().getAVariable() << '\n';
}

Outras dicas

In this case, you could define an accessor (get function) on Class1 that simply returns the result of calling getAVariable() on Class2.

You have two options:

class Class1
{
    public:
        int getAVariable()                   //Option 1, Get the int directly
        {
            return anObject.getAVariable()
        }
        Class2 getAnObject()                 //Option 2, Get a copy of the object
        {                                    
            return anObject
        } 
    private:
        Class2 anObject;
}

Option 1: is what AboutAverage suggested. But then if you had more than one private members in Class2 then you would need an accessor for each in Class1

Option 2: Is what aafonso1991 just beat me to. It returns a copy of the anObject so anObject in Class1 still isn't modified. It's the better OO choice because you won't need to create extra functions and save those lines of code. It could be an issue at run time though if Class2 is particularly large and copying it is expensive. In that case, you could create accessors of like option1 to commonly desired members of Class1

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top