【问题标题】:C++03 Resolve a circle composition when calling a member functionC++03 调用成员函数时解析圆组成
【发布时间】:2014-11-25 15:41:21
【问题描述】:

我有以下类结构。这显然不会编译。我可以转发声明 B。然后,我可以在函数调用中使用函数指针,但这不是一个好的解决方案,因为我会从 A::funcA 调用 A 中的其他其他函数,或者将 B 的声明的一部分放入标题中,这将是几百行并且很实用。

处理这种情况的首选方法是什么(其他)?

class B;

class A
{
public:
    void funcA(B* b);
    double funcA2();
    int funcA4(B* b);

private:
    E memberA1;
    E memberA2;
};

void A::funcA( B* b) {
    b->funcB(a->memberA1, a->memberA2);

class B : public BBase
{
public:
    void FuncB(E* e1, E* e2)
    {
        /* using const objects of B that are initialized 
           by B() and some other functions... */
    }

    std::vector<C*> memberB1;             // C has std::vector<A*> memberC1
};

int main() {
    calling B->memberB1.at(0)->memberC1.at(0)->funcA();
}

我有以下内容(省略一些不必要的行):

啊.h

Class B;

Class A {
    declaration of A
};

A.cpp ....

B.h

#include "A.h"
#include "BBase.h"

Class B {
    declaration of B
};

B.cpp ....

BBase.h

#include "C.h"
#include "A.h"
#include "AInterface.h"

typedef std::vector<AInterface> AList;

BBase {
   declaration of abstract BBase
};

BBase.cpp ....`

但我仍然收到错误:成员访问不完整的类型“B”。

【问题讨论】:

  • BBase.cpp中包含"B.h"?
  • 不,在cpp-s 中只包含对应的.h。例如BBase.cpp 仅具有 BBase.h
  • 在哪里你得到错误?如果您使用B,则需要B 类的完整定义,因此需要在该源文件中包含B.h 文件。
  • 我在尝试使用 B-&gt;funcB(...); 时在 A.cpp 中得到它@在B.h.
  • 您能否创建一些完整代码,Minimal, Complete, and Verifiable example,并展示给我们?

标签: c++ composition member-functions


【解决方案1】:

假设 EC 已充分声明/定义,那么您所拥有的几乎没问题。问题是您在定义B 类之前定义了A 的成员函数,请确保类B 之前已完全定义(实际类,而不是其成员函数的完整实现)你已经实现了A 成员函数。

所以是这样的:

class B;

class A { ...; void member_function(B*); ... };

class B { ...; void other_member_function(); ... };

void A::member_function(B* b) { ...; b->other_member_function(); ... }

【讨论】:

    【解决方案2】:

    我建议使用接口而不是具体的 B 类

    class B : public IB{
    };
    

    并将 IB 而不是 B 传递给 A。

    在 C++ 中更好地使用模板函数并绑定您要调用的成员函数

    a.funcA( std::bind( &B::funcB, &b, someArg );
    

    【讨论】:

    • 很遗憾我不能使用 C++11(绑定)。
    • 你可以使用 boost::bind 代替。
    猜你喜欢
    • 2013-02-15
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多