-1

Book并且Article是来自 的派生类Medium

尝试在参考书目中插入Medium/ Book/时为什么会出现此错误?Article

error: no matching function for call to '**std::reference_wrapper<Medium>::reference_wrapper()**

编译器错误

主文件

#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;
}

参考书目.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);
};

#endif

参考书目.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;
}
4

1 回答 1

2

您不应该使用reference_wrapperin 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_Sizereference_wrapper对象,但默认构造函数reference_wrapper不存在,并且无法编译代码。

您可以使用reference_wrapperwithvector但在调用需要定义默认构造函数的向量方法时会出现编译错误。

于 2017-12-16T19:39:12.550 回答