简体   繁体   中英

assignment of an protected struct member to a friend?

I have a classes that contains data in form of MyObjects like class A. I wish to Monitor the data in the MyObject objects. So I created a IMonitorable class and derived all my storage classes that contains the MyObjects from IMonitorable. Add added the IMonitorable class as a friend to my monitoring class.

class IMonitorable
{}        

class a : public IMonitorable
{
protected:
   struct myData
   {
      MyObject a;
      MyObject b;
      ...
   } data;
}

class Monitor
{
public:
   friend IMonitorable;
   AddData(a& stroage);
   AddObject(MyObject& obj);

}

This worked fine while I had one storage class with a known myData struct. I called

AddData(InstanceOfA);

and added MyObject a,b,.. to my monitoring mechanism.

Now I have several storage classes and I don't want to write an AddData method for all storage classes. I thought of having a AddObject method to be able to have a single point suitable for all storage classes.

AddObject(InstanceOfA.data.a);
AddObject(InstanceOfA.data.b);
...

But if I call this somewhere in my code gcc throws the error data.a is protected, what is right.

Is there a way to add a reference or a pointer of the protected MyObject to the Monitor without the knowledge of the structure of the storage class?

You declared struct myData as protected. friend IMonitorable declare IMonitorable as friend class that means that IMonitorable has acces to private members of Monitor class. To access private members from Monitor use getter function:

class a : public IMonitorable
{
public:
   const myData* const getData()const
   {
      return &data;
   }
   myData* getData()
   {
      return &data;
   }
protected:
   struct myData
   {
      MyObject a;
      MyObject b;
      ...
   } data;
}

Use it:

AddObject(InstanceOfA.getData()->a);

I can't see exactly what you are doing, and you confuse things by using a both as a class and then a member of myData.

But I think the issue is that that friendship is not reciprocated.

You have made IMonitorable a friend of Monitor , but that does not make Monitor a friend of IMonitorable , and incidentally even if you did make it a friend of IMonitorable it wouldn't get access to protected members of a which derives from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM