我有两个类:位置和地址。地址包含一个名为 l1 的成员,它的类型为 Location。
class Location
{
double lat, lon;
char *em;
public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
friend ostream& operator<< (ostream&, const Location &);
};
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);
};
地址构造函数:
Adress::Adress(char *des, 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);
}
}
位置构造函数:
Location::Location(int lat, int long, const char *em)
{
this->lat=lat;
this->lon=lon;
if (emi!=NULL)
{
this->em=new char [strlen (em)+1];
strcpy (this->em, em);
}
}
当我调用类地点在主函数的构造方法创建一个新的对象来自动调用位置类的构造函数,像我想要做的是:Address ("desc", l1 (43.23, 32.12, "south"), "country")
。我尝试了很多方法,但似乎都没有奏效。抱歉我的错误,我是初学者。
似乎您想将临时位置对象传递给 Address 构造函数,因此您的参数化构造函数定义应该更改为接受 const Location&,这里是您想要实现的示例代码:
class Location
{
double lat, lon;
char *em;
public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
friend ostream& operator<< (ostream&, const Location &);
protected:
private:
};
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);
}
}
Location::Location(int lat, int lon, const char *em)
{
this->lat=lat;
this->lon=lon;
if (em!=NULL)
{
this->em=new char [strlen (em)+1];
strcpy (this->em, em);
}
}
int main()
{
Adress ("desc", Location (43.23, 32.12, "south"), "country");
return 0;
}
您也不能使用对象名称调用类构造函数,因此应将 l1 更改为类名称,即位置
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句