我有一个问题实施策略模式到我的项目。我创建了所有需要的文件,但是我在主要的新调用中遇到错误,因为我似乎无法将策略初始化为我想要的。战略模式 - C++
Strategy.h
/*All the classes that implement a concrete strategy should use this
The AI class will use this file as a concrete strategy
*/
using namespace std;
class Strategy{
public:
//Method who's implementation varies depending on the strategy adopted
//Method is therefore virtual
virtual int execute() = 0;
};
我的三个战略 Aggressive.h
#pragma once
#include <iostream>
#include "Strategy.h"
class Aggressive{
public:
int execute();
};
Aggressive.cpp
#pragma once
#include <iostream>
#include "Strategy.h"
using namespace std;
class Aggressive : public Strategy{
public:
Aggressive(){}
int execute(){
cout << "The defensive player chooses to adopt an aggressive play- style" << endl;
return 0;
}
};
Defensive.h
#pragma once
#include <iostream>
#include "Strategy.h"
class Defensive{
public:
int execute();
};
Defensive.cpp
#include <iostream>
#include "Strategy.h"
using namespace std;
class Defensive : public Strategy{
public:
int execute(){
cout << "The defensive player chooses to adopt a defensive play-style" << endl;
}
};
AI.h
#pragma once
#include "Strategy.h"
class AI{
public:
AI();
AI(Strategy *initStrategy);
void setStrategy(Strategy *newStrategy);
int executeStrategy();
};
AI.cpp
#pragma once
#include "Strategy.h"
#include "AI.h"
#include "Aggressive.h"
#include "Defensive.h"
using namespace std;
class AI{
private:
Strategy *strategy;
public:
AI(){}
//Plugs in specific strategy to be adopted
AI(Strategy *initStrategy){
this->strategy = initStrategy;
}
void setStrategy(Strategy *newStrategy){
this->strategy = newStrategy;
}
//Method that executes a different strategy depending on what
//strategt was plugged in upon instantiation.
int executeStrategy(){
return this->strategy->execute();
}
};
我的临时驾驶,这与新 StrategyDriver.cpp
问题#pragma once
#include "AI.h"
#include "Strategy.h"
#include "Aggressive.h"
#include "Defensive.h"
#include "Random.h"
using namespace std;
int main(){
AI *ai(new Aggressive());
ai->executeStrategy();
}
如果有人看到我的代码的问题,任何帮助将不胜感激。我不完全确定如何初始化新AI,以实施特定的策略。
你能显示确切的错误信息吗? – Christophe 2015-03-08 22:01:26
我的错误信息是关于新的主要。错误:“Aggressive”类型的值不能用于初始化“AI”类型的实体 – 2015-03-08 22:38:50