How to access private variable from object instant

2019-03-01 13:29发布

问题:

I am trying to change a private variable of a class inside an object, which is initialized inside that class. My intention can be drawn from the simple example below. the Increment called from obj should increase the BaseClass::stuff.

template <typename ObjectType>
class BaseClass{
 public:

  int Increment(){
    return obj.Increment();
  }

 private:
  int stuff = 0;
  ObjectType obj;
};

class ObjectType{
  public:     
   int Increment ()
   {
      return BaseClass<ObjectType>::stuff++;
   };
};

int main () {
  BaseClass<ObjectType> base;
  base.Increment(); // should increase stuff by 1;
}

One way I can think of is passing stuff as parameter to obj.Increment().

Is there a way I can achieve this without passing it as a parameter?

回答1:

Your example had a few errors.
Once fixed and added a friend specifier, it should look like this:

template <typename ObjectType>
class BaseClass{
public:
    friend ObjectType;

    int Increment(){
        return obj.Increment();
    }

private:
    static int stuff;
    ObjectType obj;
};

template<typename T>
int BaseClass<T>::stuff = 0;

class ObjectType{
public:     
    int Increment ()
    {
        return BaseClass<ObjectType>::stuff++;
    };
};

int main () {
    BaseClass<ObjectType> base;
    base.Increment(); // should increase stuff by 1;
}


回答2:

1, the stuff is not a static public member, so it can not be directly implemented by ClassName::, id you want to using "BaseClass::stuff++", please change it as static public, this make all the objects of BaseClass share one stuff.

2, otherwise, ObjectType need "know" the BaseClass, ObjectType::Increment can increase the BaseClass stuff through some help funciton of BaseClass or make the ObjectType as a friend of BaseClass.

example code for ObjectType own BaseClass:

template <typename ObjectType>
class BaseClass{
public:
    void increaseStuff() {++stuff;}
.... 
}

class ObjectType
{
    BaseClass<ObjectType>& itsBase;
public:    
    ObjectType(BaseClass<ObjectType>& base) : itsBase(base) 
    int Increment ()
    {
       return itsBase.increaseStuff();
    };
};

but I think this design seems very strange, it means "I want to change something owned by me through others", why not directly change my things. in this case, I think the stuff owned by ObjectType is more better.