较大类中的两个类共享数据

时间:2012-04-03 20:30:02

标签: c++ class inheritance

我有一个包含其他两个类的对象的类。我需要其中一个类能够从另一个类中获取数据。这是一个例子。

class Nom{ /*says what we're eating*/ };
class Chew{ /*stuff that needs to know about what we are eating from nom*/ };

class BigBurrito 
{
   Nom n;
   Chew c;
};

3 个答案:

答案 0 :(得分:1)

如何将Nom实例的指针传递给Chew?沿着这些方向:

class Nom {};

class Chew
{
private:
    Nom *m_nom;
public:
    Chew(Nom *nom)
    : m_nom(nom)
    {}
};

class BigBurrito
{
private:
    Nom m_nom;
    Chew m_chew;
public:
    BigBurrito()
    : m_chew(&m_nom)
    {}
};

答案 1 :(得分:1)

您可以将指向另一个类的指针作为类的成员

class Nom{
   Chew* chew;
};
class Chew{ /*stuff that needs to know about what we are eating from nom*/ };

class BigBurrito 
{
   Nom n;  //contains pointer to c
   Chew c;
};

或通过参数将其传递给执行操作的函数。

class Nom
{
   void performOperationOnChew(Chew& c);
};
class Chew{ /*stuff that needs to know about what we are eating from nom*/ };

class BigBurrito 
{
   Nom n;
   Chew c;
   void doTheOperation()
   {
      n.performOperationOnChew(c);
   }
};

第二个选项是更清晰的OOP,因为Chew在逻辑上不属于Nom

答案 2 :(得分:0)

只需将对nNom)的引用传递给您的Chew构造函数。

相关问题