Reputation: 1281
Suppose I have a class that only has static members:
OnlyMaths.h:
#include "2DData.h"
class OnlyMaths{
public:
static double average(2DData* a); // Will call 2DData's functions
//... more static functions
private:
OnlyMaths() {} // Non-instantiable class
};
And that 2DData is a class that uses OnlyMaths:
2DData.h:
#include "OnlyMaths.h"
class 2DData{
public:
2DData(double x, double y);
double average() {
return OnlyMaths::average(this); // Uses static function
}
};
Both classes need to know each other (and their methods) in order to perform their functions, but, as I wrote it, there is a circular inclusion and it wont compile.
How do I make a "static" class like OnlyMaths
know other classes it needs in it's functions and have it's static functions called anywhere? Surely there is a correct way of doing this.
Note: Please assume that all *.h files are define protected with #ifndef ...
as usual.
EDIT:
Some circular dependencies questions, like this, are given solutions that revolve around forward declaration. In this case this is not a possibility, as not only both classes need to know each other but also they need to know each other's functions.
By the difficulty in finding a simple solution I'm starting to think that the way I'm going about the problem may not be right, so let me clarify my goal:
The goal is to have a file OnlyMaths.h
contain all the functions that do mathematics operations on all data types I have in my project. This functions can be called anywhere in the project, sometimes even inside the classes OnlyMath
's operates on.
Upvotes: 0
Views: 79
Reputation: 738
One solution is to include 2DData.h
in OnlyMaths.cpp
:
OnlyMaths.h :
class 2DData; // Declaration only.
class OnlyMaths{
public:
static double average(2DData* a); // Will call 2DData's functions
//... more static functions
private:
OnlyMaths() {} // Non-instantiable class
};
OnlyMaths.cpp :
#include <OnlyMaths.h>
#include <2DData.h>
double OnlyMaths::average(2DData* a)
{
a->method();
}
This way, 2DData
's functions are available for any OnlyMaths
's functions and vice-versa, without circular dependencies.
Upvotes: 2