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