Book和Article是从Medium派生的类。
为什么在书目中插入Medium / Book / Article时会出现此错误?
error: no matching function for call to '**std::reference_wrapper<Medium>::reference_wrapper()**

main.cc
#include <iostream>
using namespace std;
#include "Bibliography.h"
#include "Medium.h"
#include "Book.h"
#include "Article.h"
int main()
{
Bibliography p(1);
Medium m1("PN","I","Pasol nah",2017);
p.insert(m1);
cout << p;
return 0;
}Bibliography.h
#ifndef BIBLIOGRAPHY_H_
#define BIBLIOGRAPHY_H_
#include "Medium.h"
#include "Article.h"
#include "Book.h"
#include <iostream>
#include <functional>
#include <vector>
class Bibliography
{
private:
int m_Size;
std::vector<std::reference_wrapper<Medium>> v;
int index;
public:
Bibliography(int size);
void insert(Medium m);
friend std::ostream& operator<<(std::ostream& out, const Bibliography &b1);
};
#endifBibliography.cc
#include "Bibliography.h"
Bibliography::Bibliography(int size)
{
std::cout << "Bibliography created \n";
m_Size = size;
v.resize(m_Size);
index = 0;
}
void Bibliography::insert(Medium m)
{
v.push_back(m);
}
std::ostream& operator<<(std::ostream& out, const Bibliography &b1)
{
for (Medium &Medium : b1.v)
{
out << Medium.toString() << std::endl;
}
return out;
}发布于 2017-12-16 19:39:12
您不应该在reference_wrapper中使用vector,因为vector可以保留具有默认构造函数的对象,而reference_wrapper没有构造函数,请查看reference_wrapper的以下构造函数
initialization (1)
reference_wrapper (type& ref) noexcept;
reference_wrapper (type&&) = delete;
copy (2)
reference_wrapper (const reference_wrapper& x) noexcept;在这一行
v.resize(m_Size); 您希望创建m_Size reference_wrapper对象,但是reference_wrapper的默认构造函数不存在,并且无法编译代码。
您可以将reference_wrapper与vector一起使用,但是当调用向量方法时会出现编译错误,这需要定义默认的构造函数。
https://stackoverflow.com/questions/47849130
复制相似问题