Переопределение оператора CAST (я думаю, это называется downcasting)

Я довольно новичок в C++, и у меня возникла небольшая проблема, которая, вероятно, легко для других. У меня есть класс A и класс B, который расширяет класс A. У меня есть объект A, давайте назовем его a1. Я хочу понизить a1 до класса типа B, используя синтаксис: "B b1=(B)a1;"

 class IAmortizabil
 {
 public:
     virtual double getAmortizare()=0;
 };



 class Utilaj : public IAmortizabil{
 protected:
     float valInventar;
     char codUtilaj[10];
     char *denUtilaj;
     int anIntrFunct;
     int durataNormata;

 public:

     Utilaj(){
         denUtilaj=NULL;
         valInventar=0;
         anIntrFunct=0;
         durataNormata=0;
     }

     Utilaj(char *codUtilaj, char *denUtilaj, float valInventar, int      anIntrFucnt, int durataNormata){
         strcpy(this->codUtilaj, codUtilaj);
         this->denUtilaj=new char[strlen(denUtilaj)+1];
         strcpy(this->denUtilaj, denUtilaj);
         this->valInventar=valInventar;
         this->anIntrFunct=anIntrFucnt;
         this->durataNormata=durataNormata;
     }

     Utilaj(Utilaj &u)
     {
         strcpy(codUtilaj, u.codUtilaj);
         denUtilaj = new char[strlen(u.denUtilaj) + 1];
         strcpy(denUtilaj, u.denUtilaj);
         valInventar = u.valInventar;
         anIntrFunct = u.anIntrFunct;
         durataNormata = u.durataNormata;
     }


     friend ostream &operator<<(ostream &iesire, Utilaj &u)
     {
         iesire << " cod utilaj " << u.codUtilaj << endl;
         iesire << "denumire utilaj " << u.denUtilaj << endl;
         iesire << "valoare inventar " << u.valInventar << endl;
         iesire << "an intrare in functiune " << u.anIntrFunct << endl;
         iesire << " durata normata " << u.durataNormata << endl;
         return iesire;
     }

     Utilaj operator=(Utilaj &u)
     {
         strcpy(codUtilaj, u.codUtilaj);
         if (denUtilaj != NULL)
             delete[]denUtilaj;
         denUtilaj = new char[strlen(u.denUtilaj) + 1];
         strcpy(denUtilaj, u.denUtilaj);
         valInventar = u.valInventar;
         anIntrFunct = u.anIntrFunct;
         durataNormata = u.durataNormata;
         return *this;
     }



     double getAmortizare()
     {
         cout << '\n';
         if (durataNormata != 0)
             return valInventar / durataNormata;
         else {
             cout << "Durata normata este 0=>eroare";
             return 0;
         }
     }


     ~Utilaj(){
         if(denUtilaj!=NULL){
             delete[]denUtilaj;
         }
     }
 };


 class Strung :public Utilaj
 {
 protected:
     int nrBucati;

 public:
     Strung() :Utilaj()
     {
         nrBucati = 0;
     }
     Strung(char *_codUtilaj, char *_denUtilaj, float _valInventar, int _an, int _durata, int _nrBucati) :Utilaj(_codUtilaj, _denUtilaj, _valInventar, _an, _durata)
     {
         nrBucati = _nrBucati;
     }

     Strung(Strung &s) :Utilaj(static_cast< Utilaj&>(s))
     {
         nrBucati = s.nrBucati;
     }

         };

РЕДАКТИРОВАТЬ: добавил мои занятия, может быть, это помогает. Я не знаю, что здесь есть "способ сделать это", но мой учитель хочет, чтобы они были такими, и спорить с ним нет смысла.

1 ответ

Решение

В C++ вы можете преобразовать указатель на базовый тип в указатель на производный тип, используя dynamic_cast, предполагая, что он в первую очередь указывает на производный тип.

class A
{
};

class B : public A
{
};

int main()
{
    A * a = new B();
    B * b = dynamic_cast<B*>(a);

    if( b == nullptr )
    {
        // Error - "a" was not a "B" object
    }

    return 0;
}

Когда вы видите (некоторый тип)Object в C++, это приведение в стиле C, а не путь к просветлению. Это эквивалентно переинтерпретации C++ и может быть довольно опасным. Это, конечно, не должно использоваться, когда dynamic_cast достаточно.

Кроме того, в C++, когда у вас есть полиморфный тип, вы должны использовать указатель. Вы не будете приводить экземпляр объекта, но вы будете приводить указатель на объект.

Пожалуйста, Google оба "dynamic_cast" и "reinterpret_cast" для лучшего понимания обоих.

Другие вопросы по тегам