另一个类的成员对象

时间:2018-04-19 07:15:58

标签: c++ class constructor

我有两个课程:位置和地址。 Adress包含名为l1的成员,其类型为Location。

apt-get update

地址构造函数

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

}

我想要做的是当我在main函数中调用类Location的构造函数来创建一个新对象来自动调用location类的构造函数时,类似于: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); } } 。我在很多方面尝试过,但似乎没有一种方法可行。对不起我的错误,我是个乞丐。

2 个答案:

答案 0 :(得分:0)

似乎您希望将临时位置对象传递给Address构造函数,因此您的参数化构造函数定义应更改为接受const Location&amp;以下是您想要实现的示例代码:

// Get our elements
const myVideo = document.querySelector(".player__video");
const playButton = document.querySelector(".player__button");
console.log(myVideo);

function play(video) {

    if (video.paused) {
        video.play();
    } else {
        video.pause();
    }
}

playButton.addEventListener('click', play(myVideo))

此外,您不能使用对象名称调用类构造函数,因此l1应更改为类名,即位置

答案 1 :(得分:0)

使用struct,您可以使用brace-initialization,它遵循结构中变量声明的顺序。

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