C ++ деструктор вызывается перед Cout - PullRequest
0 голосов
/ 24 апреля 2018
#include <iostream>
#include <string.h>
using namespace std;


class Location
{
double lat, lon;
char *emi;

public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
void print () const;
friend ostream& operator<< (ostream&, const Location &);
void operator! ();


protected: ;

private:
};

Location::Location(int lat, int lon, const char *emi) 
{
this->lat=lat;
this->lon=lon;
if (emi!=NULL)
{
this->emi=new char [strlen (emi)+1];
strcpy (this->emi, emi);
}

}

Location::~Location()
{
if (emi!=NULL)
delete []emi;

}

Location::Location(const Location &l)
{
lat=l.lat;
lon=l.lon;
if (l.emi!=NULL)
{
emi=new char [strlen (l.emi)+1];
strcpy (emi, l.emi);
}
}
void Location::operator! ()
{
if (!(strcmp(this->emi, "north")))
strcpy (this->emi, "south");
else strcpy (this->emi, "north");
}


void Location::print() const
{
cout<<this->emi<<endl;
cout<<this->lon<<endl;
cout<<this->lat<<endl;
cout<<endl;
}
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,const Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);



protected:

private:
};


Adress::Adress(char *des,const  Location &l1, char *country)
{
if (des!=NULL)
{
this->des=new char [strlen (des)+1];
strcpy (this->des, des);
}
if (country!=NULL)
{
this->country=new char [strlen (country)+1];
strcpy (this->country, country);
}
this->l1=l1;
}

Adress::~Adress()
{
if (country!=NULL)
delete []country;
if (des!=NULL)
delete []des;
}
ostream& operator<< (ostream &os, const Adress& a){
os <<"Descrition: " << a.des<<endl;
os<<"Country: "<<a.country<<endl;
a.l1.print();
return os;
}

int main ()
{
Adress a1 ("dsad", Location (323, 34, "fdsf"), "fsdf");
cout<<a1;
}

Проблема в том, что когда я создаю объект Adress и отображаю его, все поля являются правильными, кроме «emi», которое перепутано, показывая случайный символ.Я думаю, что деструктор вызывается до того, как я его покажу.Если я удаляю деструктор Location, он работает.Как я должен решить это?Я извиняюсь за свои ошибки, но я новичок.

1 Ответ

0 голосов
/ 24 апреля 2018

Прежде всего, было бы лучше использовать std :: string, а не char *, но я объясню вашу проблему для цели образования.

Вы должны убедиться, что после создания объекта все его переменные-члены инициализированы. В случае класса Location, например; вы не инициализировали переменную-член emi, если третий аргумент конструктора - nullptr. поэтому я немного его изменил:

Location::Location(int _lat, int _lon, const char* _emi)
    : lat(_lat)
    , lon(_lon)
    , emi(nullptr)
{
    if (_emi != nullptr)
    {
        emi = new char[strlen(_emi) + 1];
        strcpy(emi, _emi);
    }
}

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

Location& Location::operator=(const Location& other)
{
    if (this != &other)
    {
        lat = other.lat;
        lon = other.lon;
        if (emi) delete[] emi;
        emi = new char[strlen(other.emi) + 1];
        strcpy(emi, other.emi);
    }
    return *this;
}
...