سؤال

I'm in a method of a derived class, loosely as follows:

Class Base
{
   private:
     int variableIWantToAccess;

}

Class Derived : public Base
{

   public someMethod() {
        variableIWantToAccess++;   <<-----ERROR

}

How do I access the variable that's declared in the base class? I'm unable to access it because it is private.

هل كانت مفيدة؟

المحلول 2

Leave the field private and create a pair of protected getter / setter methods instead (for the same reasons you wouldn't expose a public field).

Class Base
{
   private:
     int variableIWantToAccess;

   protected:
     int GetVariable() { return variableIWantToAccess; }
     void SetVariable(int var) { variableIWantToAccess = var; }

}

نصائح أخرى

You should declare it as protected instead of private.
Protected members of a class are accessible for the class descendants only.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top