我的程序中有几个类,但目前我主要关注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;
}
贷款
#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
贷款
#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()”
最佳答案
您的Loan
构造函数需要在进入主体之前默认初始化其item
,但是LibraryItem
没有默认的构造函数。
使用初始化程序列表进行成员初始化:
Loan::Loan(int id, LibraryItem i, string bdate, string ddate)
: loanID(id),
borrowDate(bdate),
dueDate(ddate),
item(i)
{
// Intentionally empty.
}
关于c++ - 尝试将对象用作类的属性时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56684966/