尝试将对象用作类的属性时出错

时间:2019-06-20 11:27:00

标签: c++ oop

我的程序中有几个类,但目前我主要关注Loan和LibraryItem类。我打算将LibraryItem对象用作Loan类的属性。当我尝试这样做时,出现错误。

我在书籍和在线上都看过类似的例子,但是找不到问题。

LibraryItem.h

#ifndef LIBRARYITEM_H
#define LIBRARYITEM_H

#include <string>

using namespace std;

class LibraryItem
{
    public:
        LibraryItem(int id, string t, int y);
        int getID();
        string getTitle();
        int getYear();
        void setCheckedOut(bool c);
        bool isCheckedOut();

    private:
        int itemID;
        string title;
        int year;
        bool checkedOut;
};

#endif // LIBRARYITEM_H LibraryItem(int id, string t, int y);

LibraryItem.cpp

#include "LibraryItem.h"

LibraryItem::LibraryItem(int id, string t, int y)
{
    //ctor
    itemID = id;    title = t;  year = y;
    checkedOut = false;
}

int LibraryItem::getID()
{
    return itemID;
}

string LibraryItem::getTitle()
{
    return title;
}

int LibraryItem::getYear()
{
    return year;
}

void LibraryItem::setCheckedOut(bool c)
{
    checkedOut = c;
}

bool LibraryItem::isCheckedOut()
{
    return checkedOut;
}

Loan.h

#ifndef LOAN_H
#define LOAN_H

#include <string>

#include "LibraryItem.h"

using namespace std;

class Loan
{
    public:
        Loan();
        Loan(int id, LibraryItem i, string bdate, string ddate);

        int getID();
        string getBorrowDate();
        string getDueDate();
        LibraryItem getItem();

    private:
        int loanID;
        string borrowDate;
        string dueDate;
        LibraryItem item;
};

#endif // LOAN_H

Loan.cpp

#include "Loan.h"

Loan::Loan()
{

}

Loan::Loan(int id, LibraryItem i, string bdate, string ddate)
{
    loanID = id;    borrowDate = bdate; dueDate = ddate;
    item = i;
}

int Loan::getID()
{
    return loanID;
}

string Loan::getBorrowDate()
{
    return borrowDate;
}

string Loan::getDueDate()
{
    return dueDate;
}

LibraryItem Loan::getItem()
{
    return item;
}  //ctor

在Loan.cpp的第3行中,出现以下错误: 错误:没有匹配的函数可以调用'LibraryItem :: LibraryItem()'

2 个答案:

答案 0 :(得分:2)

您的Loan构造函数需要在进入主体之前对其item进行默认初始化,但是LibraryItem没有默认的构造函数。

使用初始化程序列表进行成员初始化:

Loan::Loan(int id, LibraryItem i, string bdate, string ddate)
  : loanID(id),
    borrowDate(bdate),
    dueDate(ddate),
    item(i)  
{
    // Intentionally empty.
}

答案 1 :(得分:1)

您为构造函数定义了

LibraryItem::LibraryItem(int id, string t, int y)

但是您从未在类定义中声明此函数。将此行添加到您的类定义中

LibraryItem(int id, string t, int y);