我有一个包含其他两个类的对象的类。我需要其中一个类能够从另一个类中获取数据。这是一个例子。
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;
};
我有一个包含其他两个类的对象的类。我需要其中一个类能够从另一个类中获取数据。这是一个例子。
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;
};
将指针传递给Nominto的实例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)
{}
};
您可以将指向另一个类的指针作为该类的成员
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.
只需将n( Nom) 的引用传递给您的Chew构造函数。