繁体   English   中英

另一个类的成员对象

[英]Member object of another class

我有两个班:位置和地址。 地址包含一个名为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应该更改为类名称,即Location

使用struct ,可以使用brace-initialization ,它遵循struct内部变量声明的顺序。

struct Location
{
    double lat, lon;
    char *em;
};

struct Address
{
    char *des;
    Location l1;
    char *country;
};

Address address {"My address", Location{188.0, 188.0, "1 em"}, "USA"};
std::cout << address.l1.lat << ", " << address.l1.lon ; // 188.0, 188.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM