1

我正在尝试使用另一个名为“List”的类的构造函数中的初始化列表来初始化一个名为“Winery”的类的实例。问题是,当我将 Winery 构造函数交给要复制的酒厂时,它无法复制信息。

这是 Winery 类的头文件:

class Winery
{
public:

    Winery(const char * const name, const char * const location, const int acres, const int rating);
    virtual ~Winery(void);

    const char * const getName() const { return name; }
    const char * const getLocation() const { return location; }
    const int getAcres() const { return acres; }
    const int getRating() const { return rating; }

private:
    char    *name;
    char    *location;
    int     acres;
    int     rating;
};

这是我的 List 类的头文件的相关部分:

struct Node
    {
        Node(const Winery& winery);     
        Winery item;                                            
        Node *nextByName;               
        Node *nextByRating;             
    };

这是我的 List 类中的构造函数:

List::Node::Node(const Winery& winery) :
item(winery.getName(), winery.getLocation(), winery.getAcres(), winery.getRating()),
nextByName(nullptr),
nextByRating(nullptr)
{
}

从我所见,看起来我正在做我需要做的一切。我传递给构造函数的酒厂数据成员是私有的,所以我试图通过获取信息的函数来获取它们。他们的顺序和一切都是正确的。初始化它们后指针工作得很好,但信息不存在,所以我真的不知道该怎么做。如果您想知道,这是一个分配,我们必须使用初始化列表(我已经尝试过没有它们,但它也不起作用,所以我真的不知道该怎么做)。我将不胜感激任何帮助!谢谢!

编辑:这是我的酒厂构造函数:

Winery::Winery(const char * const name, const char * const location, const int acres, const int rating) :
acres(acres),
rating(rating)
{
    char *newName = new char[sizeof(name) + 1];
    char *newLocation = new char[sizeof(location) + 1];
}
4

1 回答 1

1

从它的外观来看,这些行:

char *newName = new char[sizeof(name) + 1];
char *newLocation = new char[sizeof(location) + 1];

基本上什么都不做,因为locationname字符串没有分配甚至写入,这可能是问题的根源。但是,您的acresandrating应该已正确构建。

这是我创建的工作版本(ideone here -> http://ideone.com/v98zpq

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

class Winery
{
public:
    Winery(const char * const name, const char * const location, const int acres, const int rating) :
        name(strdup(name)),
        location(strdup(location)),
        acres(acres),
        rating(rating)
    {
    }

    virtual ~Winery(void)
    {
        free(name);
        free(location);
    }

    const char * const getName() const { return name; }
    const char * const getLocation() const { return location; }
    const int getAcres() const { return acres; }
    const int getRating() const { return rating; }

private:
    char    *name;
    char    *location;
    int     acres;
    int     rating;
};

struct Node
{
    Node(const Winery& winery);
    Winery item;
};

Node::Node(const Winery& winery) :
    item(winery.getName(), winery.getLocation(), winery.getAcres(), winery.getRating())
{
}

int main()
{
    Winery winery("Mission Hill Winery", "Kelowna, BC, Canada", 646, 4);

    Node node(winery);

    printf("%s\n", node.item.getName());
    printf("%s\n", node.item.getLocation());
    printf("%i\n", node.item.getAcres());
    printf("%i\n", node.item.getRating());
}

输出:

Mission Hill Winery
Kelowna, BC, Canada
646
4
于 2014-10-11T03:31:42.130 回答