我正在学习c ++。我非常了解java和python,但是我在c ++试用中使用一点点设计模式我很生气。
这是我的文件,我认为它们是非常自动解释的,如果有问题,欢迎发表评论!
我有一个具有行为的类引擎..我想将行为子行为不同的特定行为..但是没有子类也很容易..
main.cpp:
#include "Engine.h"
int main() {
Engine e;
e.work();
return 0;
};
Engine.h:
#ifndef ENGINE_H_
#define ENGINE_H_
#include <iostream>
#include "Behaviour.h"
class Engine {
public:
Engine() {
std::cout << "Engine constructor" << std::endl;
this->b = new Behaviour(this);
};
virtual ~Engine(){};
void work() {
std::cout << "Engine work" << std::endl;
};
int getFoo() { return 42; };
private:
Behaviour * b;
};
#endif /* ENGINE_H_ */
Behaviour.h:
#ifndef BEHAVIOUR_H_
#define BEHAVIOUR_H_
#include <iostream>
#include "Engine.h"
class Behaviour {
public:
Behaviour(Engine* e) {
std::cout << "behaviour constructor, kind of abstract class" << std::endl;
this->e = e;
};
virtual ~Behaviour(){};
void work() {
std::cout << "Behaviour work" << this->e->getFoo() << std::endl;
};
protected:
Engine * e;
};
#endif /* BEHAVIOUR_H_ */
我的编译器错误:
$ rm *.gch; c++ *
In file included from Behaviour.h:5:
Engine.h:26: error: ISO C++ forbids declaration of ‘Behaviour’ with no type
Engine.h:26: error: expected ‘;’ before ‘*’ token
Engine.h: In constructor ‘Engine::Engine()’:
Engine.h:14: error: ‘class Engine’ has no member named ‘b’
Engine.h:14: error: expected type-specifier before ‘Behaviour’
Engine.h:14: error: expected ‘;’ before ‘Behaviour’
In file included from Engine.h:5:
Behaviour.h:11: error: expected ‘)’ before ‘*’ token
Behaviour.h:23: error: ISO C++ forbids declaration of ‘Engine’ with no type
Behaviour.h:23: error: expected ‘;’ before ‘*’ token
Behaviour.h: In member function ‘void Behaviour::work()’:
Behaviour.h:19: error: ‘class Behaviour’ has no member named ‘e’
Engine.h: In constructor ‘Engine::Engine()’:
Engine.h:14: error: no matching function for call to ‘Behaviour::Behaviour(Engine* const)’
Behaviour.h:7: note: candidates are: Behaviour::Behaviour()
Behaviour.h:7: note: Behaviour::Behaviour(const Behaviour&)
我认为我需要一些前瞻性声明,但我不确定并查看教程并进行一些试验并不能解决我的问题。
答案 0 :(得分:4)
在Engine.h
中使用前向声明替换include:
#include "Behaviour.h"
与
class Behaviour;
class Engine;
内的Behavior.h
相同。
因为你有一个循环依赖,你需要使用前向声明而不是包含。
您还需要在cpp
文件中分隔实施。仅使用转发声明不会让您致电this->b = new Behaviour(this);
。
另外,请花一些时间重新考虑您的设计。这种依赖通常是代码味道。
答案 1 :(得分:1)
你有一个循环依赖问题,通常,你必须在CPP文件中实现Behavior的方法,但它可能不是最好的做法。 我认为Engine在您的应用程序中是一个非常重要的抽象概念,您可以使用纯虚拟类作为接口定义来描述它。
例如:
IEngine.h
class IEngine {
public:
void work() = 0;
};
IEngine* newEngine();
EngineImpl.h
class EngineImpl : public IEngine {
public:
void work();
};
EngineImpl.cpp
void EngineImpl::work();
// do some works
}
IEngine* newEngine() {
return new EngineImpl();
}
现在,只需包含IEngine.h,就可以通过IEngine在代码中的任何位置使用引擎。你甚至可以通过定义:
来建立一个引擎单例IEngine.h:
IEngine* sharedEngine();
EngineImpl.cpp
IEngine* sharedEngine() {
static IEngine *engineInst = 0;
if (!engineInst)
engineInst = new EngineImpl();
return engineInst;
}