假设我有一个只有静态成员的类:
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
};
2DData是一个使用OnlyMaths的类:
2DData.h :
#include "OnlyMaths.h"
class 2DData{
public:
2DData(double x, double y);
double average() {
return OnlyMaths::average(this); // Uses static function
}
};
两个类都需要相互了解(及其方法)才能执行它们的功能,但是,正如我所写,它有一个循环包含,它不会编译。
如何使像OnlyMaths
这样的“静态”类知道它在函数中需要的其他类,并将它的静态函数调用到任何地方?当然有一种正确的方法可以做到这一点
注意:请假设所有* .h文件都像往常一样使用#ifndef ...
进行保护。
编辑:
一些循环依赖问题,如this,给出了围绕前向声明的解决方案。在这种情况下,这是不可能的,因为不仅两个类都需要彼此了解,而且他们还需要了解彼此的功能。
由于难以找到一个简单的解决方案,我开始认为我正在解决问题的方式可能不对,所以让我澄清一下我的目标:
目标是让文件OnlyMaths.h
包含对我项目中的所有数据类型进行数学运算的所有函数。这个函数可以在项目的任何地方调用,有时甚至可以在类OnlyMath
内部进行操作。
答案 0 :(得分:2)
一种解决方案是在2DData.h
中加入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();
}
这样,2DData
的函数可用于任何OnlyMaths
的函数,反之亦然,没有循环依赖。