在类之间传递信息

时间:2012-11-01 05:28:21

标签: c++ class

我打算试试这句话。如果需要,请要求澄清。

我有一个类(我们称之为类a),它有一个方法可以使用ifstream打开文件并从文件中读取数据。我还有另一个班级(我们称之为班级b)。我需要从a类中获取该信息并将其传递给b类。执行此操作的方法是从类b调用的。我以为我可以

  1. 从a-> b
  2. 声明继承
  3. 声明好友功能或
  4. 只需使用类a作为类型声明类b中的var,然后使用a.function运行函数。
  5. 但无论如何,结果总会产生一个?如果我自己运行类a,它工作正常(读取数据并输出数据)。

    你能不能在类之间运行infile.get函数吗?

1 个答案:

答案 0 :(得分:0)

通常,您应该在两个类之间定义API。在这种情况下,您的API可以是B类中的一个方法,该方法期望从A类调用您需要传输的数据。像这样:

//B header file
struct dataType;
class B
{
    //...
public:
    statusType passData(dataType &x);
};

//A header file
struct dataType   //shared data type between the 2 classes
{
    //internal structure of your data
};

class A
{
    B *objB;   //link to B instance (the receiver)
    statusType acquireData();
};

//cpp file
#include "A.h"
#include "B.h"
statusType B::passData(dataType &x)
{
    //do whatever you need with the data
}

statusType A::acquireData()
{
    //do your reading from file here into x
    objB.passData(x);
}

此示例演示了在A和B类之间创建简单接口。 任何其他更紧密的关系,例如继承或组合,也是可能的,但这实际上取决于您的要求,并暗示比您所说的更强的关系。否则它将(即使有效)设计缺陷。