【问题标题】:C++ Inheritance and CastingC++ 继承和强制转换
【发布时间】:2015-10-24 08:15:36
【问题描述】:

我在 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();

【问题讨论】:

  • 应该是static_cast<GT1*>(P)->getArcos();。但我不相信你的整体设计。
  • ...他说,无视繁重的警告... :)
  • 这肯定会导致难以诊断出沿线某处的问题。

标签: c++ inheritance casting


【解决方案1】:

首先,您似乎是从课堂外分配给受保护的成员Hijo,这是不好的做法和/或不起作用。恕我直言,您应该改用 setter。

其次,您的核心问题是沿继承层次结构向下转换:您有一个指向基类的指针,并希望像使用指向派生类的指针一样使用它.原则上,这是完全可能的。有两种选择:

  • 如果您确定指向基类的指针实际上指向派生类的某个对象,请使用static_cast
  • 否则使用dynamic_cast。这需要 RTTI 编译,但安全,如果指针无法强制转换,则返回空指针。

如上面的 cmets 所述,您的设计可能看起来很糟糕。或许可以考虑使用virtual 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2011-11-17
    • 2011-01-05
    • 2010-11-30
    • 2012-02-04
    相关资源
    最近更新 更多