简体   繁体   English

通过组合访问数据成员

[英]accessing data member through composition

I have a struct obj in my base class.我的基类中有一个 struct obj 。 I don't know how to access the data members of the struct through Derv1 class (Derived from the base class).我不知道如何通过 Derv1 类(派生自基类)访问结构体的数据成员。 I tried making both Base and Derv1 a friend of struct - it still tells me ' data member is private' (its private in Base only).我尝试让 Base 和 Derv1 成为 struct 的朋友 - 它仍然告诉我“数据成员是私有的”(它仅在 Base 中是私有的)。

example :例子 :

struct A{
    public :
        int total;
        //some stuff
};
class MyClass{ // [Base] class
    private:
      A var1;
};

class Derv1{
    private:
        //some stuff
        public void display_var1(Derv1 x){
            return x.var1.total;
        }  // trying to return the value of A.total
};

I hope this makes sense so that you can help me out .. Thank You kindly,我希望这是有道理的,以便您可以帮助我......谢谢你,

i think you must extend your Derv1 class into the Base class:我认为您必须将您的 Derv1 类扩展到 Base 类中:

class Derv1: public MyClass{

to inherit the members of the base class继承基类的成员

First, you have to make sure that Derv derives from MyClass .首先,您必须确保Derv派生自MyClass

class Derv1 : public MyClass { ... };

and then, you will need to figure out the best way to display the variable.然后,您需要找出显示变量的最佳方式。

My suggestion:我的建议:

  1. Create a virtual member function in the base class.在基类中创建一个virtual成员函数。
  2. Override the function in the derived class.覆盖派生类中的函数。
  3. Make sure to call the base class implementation in the derived class implementatin.确保在派生类实现中调用基类实现。

class MyClass { // [Base] class

    public:

        virtual void display() const
        {
           // Display var1 anyway you wish to.
        }

    private:
      A var1;
};

class Derv1 : public MyClass {

    public:

        virtual void display() const
        {
           // Call the base class implementation first
           MyClass::display():

           // Display anything else that corresponds to this class
        }

    private:
        //some stuff
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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