【发布时间】:2018-04-24 15:54:21
【问题描述】:
#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 析构函数,它就可以工作。我应该如何解决?我很抱歉我的错误,但我是新手。
【问题讨论】:
-
请编辑您的问题以包含minimal reproducible example
-
请贴出真实代码,即使添加了缺失的部分也无法编译
-
你没有为
Location写operator=是故意的吗?这将使用简单地复制指针的默认实现。这个指针指向当原始实例离开作用域时被删除的东西。 -
这显然不是您自己实际编译和测试的代码。请edit修复错误;您还应该包含必要的标题和
main()函数以使其成为minimal reproducible example。附:拼写:地址(两个d) -
不相关,但你为什么写课程而不使用
std::string?
标签: c++ class destructor