[英]C++ How to access derived class member from base class pointer without using a static_cast or dynamic_cast?
[英]C++ dynamic_cast base class pointer to derived class pointer
我正在尝试使用一种非常简单的编程语言,使某人可以在Flex / Bison中为学校项目玩战舰游戏。 为了存储我的变量,我有一个称为symbol_table的映射,该映射以一个字符串作为键,并以Variable *作为其值。 继承树如下:
class Expression {
public:
Type type;
virtual ~Expression(){} //to make it polymorphic
};
class Variable : virtual public Expression {
public:
char* name;
Variable* next;
virtual ~Variable(){ //also for polymorphism
delete name;
delete next;
}
};
class Player : virtual public Variable{
public:
std::string playerName;
std::vector<GameBoat> playerBoats;
Grid opponentGrid;
Grid playerGrid;
Player(std::string playerName){
this->playerName = playerName;
}
bool addBoat(std::string boatName, char scolumn, int srow, bool vertical){
//make new boat here and then push it back to the vector
GameBoat newBoat(boatName); //this works --> makes a valid boat
if(newBoat.assignedValue){
playerBoats.push_back(newBoat); //SEGMENTATION FAULT HAPPENS HERE
return true;
}else{
return false;
}
}
};
class Computer : public Player{
public:
Computer(std::string playerName) : Player(playerName){}
};
当我将Player指针和Computer指针放到地图中时,一切工作都很好,但是当我尝试使用dynamic_cast将基本Variable *向下转换为Player *或Computer *时,再次尝试获取这些值时,已投射Player的所有属性*或Computer *为NULL,因此出现“ Segmentation Fault:11”错误。 但是,我可以访问Player和Computer类中的类方法。
Variable* var = get_symbol($1);
if (var == NULL) {
sprintf(errormsg, "%s not found.\n", $1);
yyerror(errormsg);
}else if(var->type == PlayerType){
Player* myPlayer = dynamic_cast<Player*>(var); //Cast var to Player*
myPlayer->addBoat("aircraftcarrier", 'a', 1, true); //Enters this function
}else if(var->type == ComputerType){
Computer* myComputer = dynamic_cast<Computer*>(var); //Cast var to Computer*
myComputer->addBoat("aircraftcarrier", 'a', 1, true); //Enters this function
}
如何访问派生类的方法,但不能访问派生类的属性? 我正在使用多态性,dynamic_cast不会返回NULL值(否则程序将永远不会输入函数并立即给出细分错误)。
addBoat
函数不是虚拟的,因此在调用它之前无需取消引用myPlayer或myComputer,因此,直到在该函数的后面,您都不会遇到段错误。
所有成员函数都有一个隐式this
参数。 您可以认为addBoat
等同于自由函数bool addBoat(Player* this, std::string boatName, char scolumn, int srow, bool vertical)
。 没有什么特别之处this
被空或者直到你真正取消对它的引用的功能。
要解决实际问题,在调用函数之前,应检查myPlayer和myComputer是否不为NULL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.