gpt4 book ai didi

c++ - 尝试在 C++ 中减少设计模式

转载 作者:太空宇宙 更新时间:2023-11-04 16:26:57 25 4
gpt4 key购买 nike

我正在学习 C++。我非常了解 Java 和 Python,但我对在我的 C++ 试验中使用一些花哨的设计模式感到很生气。

这是我的文件,我认为它们很自动解释,如果有任何问题,欢迎评论!

我有一个具有行为的引擎类..我想将行为 segmentation 为不同的特定行为..但是没有子类也很容易..

main.cpp :

#include "Engine.h"

int main() {
Engine e;
e.work();
return 0;
};

引擎.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_ */

行为.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&)

我想我需要一些前向声明(forward declaration),但我不确定,浏览教程并进行一些试验根本无法解决我的问题。

最佳答案

Engine.h 中用前向声明替换包含:

#include "Behaviour.h"

class Behaviour;

类 Engine;Behavior.h 中也是如此。

因为你有一个循环依赖,你需要使用前向声明而不是包含。

您还需要在 cpp 文件中分离实现。 单独的前向声明不会让您调用 this->b = new行为(this);.

此外,请花一些时间重新考虑您的设计。这种依赖通常是一种代码味道。

关于c++ - 尝试在 C++ 中减少设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10721459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com