两个依赖结构的内联方法?

时间:2016-11-02 06:16:58

标签: c++ include inline

我想内联我的两个结构。但他们互相指针。像下面的代码:

A.H

#ifndef A_H
#define A_H

#include "b.h"

struct A
{
    B* b;
    int value;

    A();
    void Inc();
};

#endif // A_H

A.cpp

#include "a.h"

A::A()
{
    b = new B(this);
}

void A::Inc()
{
    b->value++;
}

B.h

#ifndef B_H
#define B_H

struct A;

struct B
{    
    A* a;
    int value;

    B(A* a);
    void Inc();
};

#endif // B_H

B.cpp

#include "b.h"
#include "a.h"

B::B(A *a)
{
    this->a = a;
}

void B::Inc()
{
    a->value++;
}

的main.cpp

#include <iostream>
#include <a.h>

using namespace std;

int main()
{
    A a;
    a.value = 0;
    a.b->value = 0;
    a.Inc();
    a.b->Inc();
    cout << a.value << endl;
    cout << a.b->value << endl;
    return 0;
}

我无法在任何地方使用关键字inline,因为它会向我显示错误undefined reference to methods

基于here,我可以在头文件中定义我的方法,但这会迫使我在文件#include <a.h>中使用b.h。但是由于重复包含,这会给我另一个错误。

现在我如何内联两种Inc方法?

2 个答案:

答案 0 :(得分:0)

无法在struct定义的主体中内联两个相互依赖的struct的所有成员函数。通过定义struct定义体外的函数并明确使用inline关键字,可以内联所有成员函数。但是,如果使用两个.h文件来定义struct/class,则会变得混乱。

以下是实现成员函数的一些选项。

选项1

仅使用.h文件中的前向声明。实现.cpp文件中的所有函数。没有内联成员函数。

选项2

A中使用B.h的前瞻性声明,但在B中使用A的完整定义。 在这种情况下,A的所有成员函数都可以内联,但B的成员函数不能内联。它们需要在.cpp文件中实现。

选项3

选项2

中撤消AB的角色

B中使用A.h的前瞻性声明,但在A中使用B的完整定义。 在这种情况下,B的所有成员函数都可以内联,但A的成员函数不能内联。它们需要在.cpp文件中实现。

答案 1 :(得分:0)

a.hb.h保持不变,a.cppb.cpp合并到包含带有ab_inl.hpp装饰器的方法和构造函数的inline ** (或者您可以让构造函数位于各自的.cpp文件中)main.cpp(或任何其他需要它的文件)包含ab_inl.hpp

<子> ** 因为编译器可以自由地忽略inline限定符,所以我更喜欢术语“decorator”

以下所有内容+ a.h + b.h只编译花花公子:

档案ab_inl.hpp

#ifndef _AB_INL
#define _AB_INL

#include "a.h"

// included by a.h anyway
// #include "b.h"

inline A::A() : b(0), value(0)
{
    b = new B(this);
}

inline void A::Inc()
{
    b->value++;
}

inline B::B(A *a) : a(0), value(0)
{
    this->a = a;
}

inline void B::Inc()
{
    a->value++;
}

#endif // _AB_INL

档案main.cpp

#include "ab_inl.hpp"


int main()
{
    using std::cout;
    using std::endl;

    A a;
    a.value = 0;
    a.b->value = 0;
    a.Inc();
    a.b->Inc();
    cout << a.value << endl;
    cout << a.b->value << endl;
    return 0;
}