C++对象返回时清除动态数组

发布于 2024-12-20 08:11:17 字数 800 浏览 1 评论 0原文

我目前正在做一项作业(所以我不想发布完整的代码),试图实现 Bag 抽象数据类型。

下面是我当前正在尝试实现的方法:

template <typename T>
Bag<T> Bag<T>::operator+ (const Bag<T>& bag) {
    int sizeofCurrentMultiset = cardinality_;
    int sizeofPassedMultiset  = bag.cardinality_;
    int totalSize = sizeofCurrentMultiset + sizeofPassedMultiset;

    Bag<T> newBag(totalSize);

    for (int i = 0; i < sizeofCurrentMultiset; i++) {
        newBag.insert(array_[i]);
    }

    for (int i = 0; i < sizeofPassedMultiset; i++) {
        newBag.insert(bag.array_[i]);
    }

    return newBag;
}

我将元素存储为动态数组。

我的问题是,当新包返回时,我可以很好地打印基数(打印到 4,原始包每个有两个元素),但动态数组不包含数字(它打印出一些随机数,例如-1789102)。然而,当我在退回袋子之前尝试打印出这些元素时,它打印得很好。

毫无疑问,这将是一件微不足道的事情,但我很感激您的帮助。

谢谢。

I'm currently working on an assignment (so I'd rather no post the full code) trying to implement a Bag abstract data type.

Below is a method which I am currently trying to implement:

template <typename T>
Bag<T> Bag<T>::operator+ (const Bag<T>& bag) {
    int sizeofCurrentMultiset = cardinality_;
    int sizeofPassedMultiset  = bag.cardinality_;
    int totalSize = sizeofCurrentMultiset + sizeofPassedMultiset;

    Bag<T> newBag(totalSize);

    for (int i = 0; i < sizeofCurrentMultiset; i++) {
        newBag.insert(array_[i]);
    }

    for (int i = 0; i < sizeofPassedMultiset; i++) {
        newBag.insert(bag.array_[i]);
    }

    return newBag;
}

I'm storing the elements as a dynamic array.

My problem is that when the new bag is returned, I can print the cardinality fine (prints to 4, the original bags had two elements each), but the dynamic array doesn't contain the numbers (it prints out some random numbers such as -1789102). However when I try print out the elements before the bag is returned, it prints out fine.

No doubt it will be something trivial, but I'd appreciate the help.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烂柯人 2024-12-27 08:11:17

您需要为您的 Bag 类编写一个复制构造函数。看起来您正在获取默认构造函数,它只对您的类进行浅表复制。这就是为什么基数成员可以,但动态数组却不行。当 operator+ 函数返回 Bag 对象时,将调用复制构造函数。

You need to write a copy constructor for your Bag class. Looks like you are getting the default constructor which only does a shallow copy of your class. This is why the cardinality member is ok but your dynamic array is not. The copy constructor is called when your operator+ function returns the Bag object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文