我有一個問題實施策略模式到我的項目。我創建了所有需要的文件,但是我在主要的新調用中遇到錯誤,因爲我似乎無法將策略初始化爲我想要的。戰略模式 - 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