所以我基本上试图在任务规划器上做一个*,因为行动通常有成本(风险,时间,花费的资源等)和奖励(效果),所以我想把它作为一个*问题,但为此我做了每个动作作为一个类,每个都有一个ID和一个计算效果的函数,我的理解是,因为一切都不同,我必须将它们分成不同的类,继承相同的基础以确保它们都具有相同的内容,但只是每个不一样。
现在的问题是我如何定义类,ActionID是在子类中声明的,而不是在基类中声明的,当我这样做时
vector<ActionBase> action_set = {a_forward,a_curve_l};
for (auto action : action_set)
{
Serial.print("%d", action->ActionID);
}
Serial.print("\n");
无法打印action ID,错误消息说“class ActionBase”没有名为“ActionID”的成员;您指的是“ActionBase”吗?
在标题操作中.h
class ActionBase{
public:
double Hcost; //Heuristic of action
double Gcost; //negative constrain/cost of action
double eX,eY,eTheta; //effect of the action
int spd_l=0;
int spd_r=0;
};
class moveForward : public ActionBase{
const int ActionID = 1; //ID of the action
void get_effect(double cX,double cY,double cTheta){
eX = cX + unit_dist*cos(cTheta);
eY = cY + unit_dist*sin(cTheta);
eTheta = cTheta;
}
void exe_action(){
digitalWrite(LD_PIN,0);
digitalWrite(RD_PIN,0);
analogWrite(LS_PIN, walk_spd);
analogWrite(RS_PIN, walk_spd);
spd_l = walk_spd;
spd_r = walk_spd;
}
}a_forward;
class moveCurve_l : public ActionBase{
const int ActionID = 2; //ID of the action
void get_effect(double cX,double cY,double cTheta){
}
void exe_action(){
digitalWrite(LD_PIN,0);
digitalWrite(RD_PIN,0);
analogWrite(LS_PIN, walk_spd);
analogWrite(RS_PIN, run_spd);
spd_l = walk_spd;
spd_r = run_spd;
}
}a_curve_l;
vector<ActionBase> action_set = {a_forward,a_curve_l};
在主代码中:
void loop() {
Serial.print("Action ID");
for (auto action : action_set) // access by reference to avoid copying
{
Serial.print("%d", action.ActionID);
}
Serial.print("\n");
}
以我的理解,它应该打印Action ID1 2,但截至目前,它是错误消息“class ActionBase”没有名为“ActionID”的成员;您指的是“ActionBase”吗?
您的代码中至少有 2 个问题:
ActionBase
不包含成员 ActionID
(仅派生类包含它)。action.ActionID
时出现错误的原因,其中 action
的类型为 ActionBase
(因为它是 vector<ActionBase> action_set
中的元素)。ActionID
添加到 ActionBase
(并将其从所有派生类中删除)。
vector<ActionBase> action_set
按值存储ActionBase
类型的元素。这意味着当您尝试存储派生类的对象时(就像我想象的 a_forward
和 a_curve_l
一样),它们会被 sliced 。这不是你想要的。action_set
更改为指向 vector
的指针 ActionBase
。std::vector<std::unique_ptr<ActionBase>>
。