开发者

Derived class function

class Base
{
   protected: 
      int data;
   public:
      virtual 开发者_C百科int getData() { return data; }
      virtual void setData(int value) { data = value; }
};

class Child : protected Base
{
   public:
   void setData(int value)
   {
       Base::setData(value);
       cout << "Data is set.\n";
   }
};

class Worker
{
   private:
      Child obj;
   public:
      void setGlobalData(int val)
      {
         obj.setData(val); // This is normal
      }

      int getGlobalData()
      {
         return obj.getData();  // Line 140, Error
      }
};

Error during compiling of file with Worker class:

Base.hpp: In member function ‘int Worker::getGlobalData()’:
Base.hpp:22:19: error: ‘virtual int Base::getData()’ is inaccessible
Worker.cpp:140:34: error: within this context
Worker.cpp:140:34: error: ‘Base’ is not an accessible base of ‘Child’


Did you actually make it a public base class?

//            vvvvvv important
class Child : public Base

Otherwise it's private, and you get errors similar to what you have, namely:

‘Base’ is not an accessible base of ‘Child’


This compiles:

class Base
{
   protected: 
      int data;
   public:
      virtual int getData() {return data;}
      virtual void setData(int value) { data = value; }
};

class Child : public Base
{
   public:
   void setData(int value)
   {
       Base::setData(value);
       cout << "Data is set.\n";
   }
};

class Worker
{
   private:
      Child obj;
   public:
      void setGlobalData(int val)
      {
         obj.setData(val); // This is normal
      }

      int getGlobalData()
      {
         return obj.getData();
      }
};


Except for clas -> class and virtua -> virtual your code is perfectly fine. There is absolutely nothing wrong with it. Since literally this doesn't compile because of the typos I suspect your original code was a bit different in that the derivation of Child from Base was private or that getData was private.


class Worker not clas Worker

In Worker class, obj.setData(val); is attempting to access a private member of Child class.


Since the current existing version of the code has Child subclassing Base via protected inheritance, the public functions in Base become protected in Child, so Worker can not access them via Child object.


Class Child inherits class Base as protected, so the member function Child::getData() is not publically accessible to clients of Child.

As everyone else here said, changing the inheritance of Base to public is one way to fix it.

class Child: public Base

Also note that casting your Child object to type Base also makes the function Base::getData() of the object publically accessible.

return static_cast<Base *>(&obj)->getData();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜