错误:隐式声明的复制构造函数定义

5
我正在处理一个关于Qt C++项目的问题。这是我新学习的一部分,我感到有些困惑。我已经创建了一些类,如资产类,又派生出股票、债券和储蓄等类。所有这些都没有问题。然后,我创建了一个名为AssetList的类,继承自QList,但是在这个类中我遇到了问题。
以下是我目前编写的代码。
AssetList.h
#ifndef ASSET_LIST_H
#define ASSET_LIST_H

#include "Asset.h"
#include <QString>

class AssetList : public QList<Asset*>
{
public:
    AssetList(){}
    ~AssetList();
    bool addAsset(Asset*);
    Asset* findAsset(QString);
    double totalValue(QString);
};

#endif

AssetList.cpp

#include "AssetList.h"

AssetList::AssetList(const AssetList&) : QList<Asset*>(){}
AssetList::~AssetList()
{
    qDeleteAll(*this);
    clear();
}

bool AssetList::addAsset(Asset* a)
{
    QString desc = a->getDescription();
    Asset* duplicate = findAsset(desc);

    if(duplicate == 0)
    {
        append(a);
        return true;
    }
    else
    {
        delete duplicate;
        return false;
    }
}

Asset* AssetList::findAsset(QString desc)
{
    for(int i = 0 ; i < size() ; i++)
    {
        if(at(i)->getDescription() == desc)
        {
            return at(i);
        }
    }

    return 0;
}

double AssetList::totalValue(QString type)
{
    double sum = 0;

    for(int i = 0 ; i < size() ; i++)
    {
        if(at(i)->getType() == type)
        {
            sum += at(i)->value();
        }
    }

    return sum;
}

我目前遇到的错误是编译错误: error: definition of implicitly declared copy constructor。我不太确定这意味着什么,我已经在谷歌上搜索并查看了教科书,但没有找到很多信息。有人可以帮助我或指导我如何解决吗?
提前感谢!
1个回答

11

你可以定义一个复制构造函数:

AssetList::AssetList(const AssetList&) : QList<Asset*>(){}

但是你没有在 AssetList 类中进行声明。

你需要添加它:

class AssetList : public QList<Asset*>
{
public:
    AssetList(){}
    ~AssetList();
    AssetList(const AssetList&);  // Declaring the copy-constructor

    ...
};

如果我只是从AssetList.h文件中删除声明,我会得到完全相同的错误:/ 或者我误解了你的意思。 - Nick Corin
@nickcorin:你需要在类定义中添加一个声明:AssetList(const AssetList&) - Mike Seymour
@nickcorin 在你展示的头文件中,没有拷贝构造函数的声明。你需要将其添加到类中。 - Some programmer dude
对不起,我误解了你的意思!非常感谢,这个完美地解决了我的问题! :) 你能解释一下为什么我需要空构造函数和复制构造函数,以及“复制构造函数”究竟是用来做什么的吗? - Nick Corin
1
@nickcorin 这是用于当你执行例如 AssetList l1; AssetList l2 = l1; 时。在第二个声明中,复制构造函数将在 l2 对象上调用,并将 l1 作为参数传递。您可能还想阅读有关三法则的内容。 - Some programmer dude

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接