[英]C++ Inheritance and Casting
我在C ++中有这两个类
Problema
这是我的超类
class Problema
{
protected:
string tipo;
int N;// GT1 # vertex ; SP5
int M;// GT1 # edges ; SP5
int K;// GT1 covering ; SP5
Problema *Hijo;
public:
//void readProblema(std::ifstream& file); // Lee un problema de un archivo
void Print();
Problema(std::string name);
Problema();
int geneSize(); // tama˜no del gen
float fitness(gene x); // c´alculo del fitness
std::string name; // hilera que indica el nombre del problema
void readProblema(std::ifstream& file);
Problema* getHijo(){return Hijo;}
string getTipo(){return tipo;}
int getN(){return N;}
int getM(){return M;}
int getK(){return K;}
int toint(std::string s);
};
GT1
是Problema
的子类
class GT1 : public Problema
{
public:
void Print();
GT1(int N,int M, int K,int **arcos);
int** getArcos(){return arcos;}
private:
int **arcos;
};
因此,如果要执行此操作,调用getArcos()
方法的正确方法是:
Problema *Prob= new Problema();
Prob->Hijo = new GT1(X,Y,Z);
Problema *P = Prob->getHijo();
int **arcos = (GT1)P->getArcos();
首先,您似乎正在从课堂之外分配一个受保护的成员Hijo
,这是一种不好的做法,并且/或者不起作用。 您应该改用二传手,恕我直言。
其次,您的核心问题是沿继承层次结构向下转换 :您有一个指向基类的指针,并且想要像使用指向类的指针一样使用它。 原则上,这是完全可能的。 有两种选择:
static_cast
。 dynamic_cast
。 这需要编译RTTI,但是很安全,如果无法强制转换指针,则返回空指针。 如以上评论所述,您的设计可能看起来很破损。 也许考虑使用virtual
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.