Wednesday 15 April 2015

c++ - Circular Dependency - (how to let struct A refer to struct B, and struct B refer to struct A) -



c++ - Circular Dependency - (how to let struct A refer to struct B, and struct B refer to struct A) -

i have header file struct called vector4.

(vector4.h)

struct vector4 { float values[4]; // ..... methods ..... };

i have header file struct called matrix4.

(matrix4.h)

struct matrix4 { float values[16]; // ..... methods ..... };

i want add together fellow member function them both, multiply() takes other struct parameter.

i can add together matrix4.h vector4.h , add together method multiply().

if seek , add together vector4.h matrix4.h (obviously) circular reference.

how can around please, if @ all?

edit:

@mikeseymour, have written assumed meant, doesn't work.

bar.h

#ifndef bar_h #define bar_h template <typename t> struct foo; template <typename t> struct bar { t t; t multiply(const foo<t>& foo) const; }; #endif // bar_h

foo.h

#ifndef foo_h #define foo_h template <typename t> struct bar; template <typename t> struct foo { t t; t multiply(const bar<t>& bar) const; }; #endif // foo_h

bar.cpp

#include "foo.h" #include "bar.h" bar<t>::multiply(const foo<t>& foo) const { homecoming t * foo.t; }

foo.cpp

#include "foo.h" #include "bar.h" foo<t>::multiply(const bar<t>& bar) const { homecoming t * bar.t; }

you'll need declare each class before class needs refer it:

// vector4.h struct matrix4; struct vector4 { // ... void multiply(matrix4); }; // matrix4.h struct vector4; struct matrix4 { // ... void multiply(vector4); };

the function definitions, need total definitions of both classes, have outside class definitions.

if classes templates, function definitions have in headers, structured appear after both class definitions. 1 approach include each header other, after header's definition:

#ifndef bar_h #define bar_h template <typename t> struct foo; template <typename t> struct bar { t t; t multiply(const foo<t>& foo) const; }; #include "foo.h" template <typename t> t bar<t>::multiply(const foo<t>& foo) const { homecoming t * foo.t; } #endif // bar_h

or might define functions in separate headers; they'll available when include headers

// bar_multiply.h #include "foo.h" #include "bar.h" template <typename t> t bar<t>::multiply(const foo<t>& foo) const { homecoming t * foo.t; }

or, since classes tightly coupled, might consider defining both in same header.

c++ header circular-dependency

No comments:

Post a Comment