简体   繁体   中英

forward definition of c++ class member functions

I'm writing a small generator which outputs c++ classes in a single cpp file from a tree object structure ( order of output of classes is given by this tree, so its fixed).

To keep it simple I would prefer if there is a way to keep it all in one file.

The problem is that these classes sometimes interact with each other using the member functions and there is the case that forward declarations arent working.

Example:

#include <iostream>

using namespace std;


class B;
B* global_b=NULL;

class A;
A* global_a=NULL;

class A {

    public:
    A() {}
    ~A() {}

    void accessB()
    {
        global_b->setValue(1);
    }

    int getValue()
    {
        return 2;
    }

};

class B {
    public:
    B() : j(0) {}
    ~B(){}

    void setValue(int i)
    {
        j = i + global_a->getValue();
    }
    int j;
};


int main()
{
    global_b = new B();
    global_a = new A();

    global_a->accessB();
    cout << "Hello world!" << endl;
    return 0;
}

Any suggestions/ideas? Thanks.

Typically, you'd do this:

class A {

    public:
    A() {}
    ~A() {}

    void accessB();
  ...
};

Then somewhere after both A and B are declared:

void A::accessB()
{
    global_b->setValue(1);
}

Your global values should probably be class statics.

To get forward declaration working you should specify the classes without any inline functions. Then later in the file you can write:

inline void B::setValue(int i)
{
  j = i + A::global.getValue();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM