c 击曲线在代表前打电话给COUT

c++ destructor called before cout

本文关键字:打电话 COUT 曲线      更新时间:2023-10-16
#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;
}

问题是,当我创建一个地址对象并显示它时,所有字段都是正确的,但是" EMI"搞砸了,显示一个随机的字符。我认为在显示灾权之前,请调用攻击函数。如果我删除位置驱动器,则可以工作。我应该如何解决?我为自己的错误感到抱歉,但我是新手。

首先,最好使用std :: string而不是char*,但我会解释您的教育目标问题。

您必须确保构造对象后,其所有成员变量均已初始化。例如,以位置类别为例;如果构造函数的第三个参数为nullptr,则不会初始化EMI成员变量。所以我更改了一点:

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;
}