c++ - "no matching function"在自定义类型上使用push_back时调用错误

标签 c++ push-back

尝试推回自定义类型的对象时出现此错误。代码如下:

class Item_base    
{
    public:     
    Item_base(string isbn=" ", int num=0):book(isbn),number(num){}    
    Item_base(Item_base &I):book(I.book),number(I.number){cout<<"\nCopy Constructor"<<endl;}    
    Item_base &operator=(Item_base &d){if (this != &d){this->book=d.book;this->number=d.number;cout<<"\nAssignment Operator"<<endl;return *this;}else{cout<<"\nAssignment Operator"<<endl;return *this;}}    
    ~Item_base(){cout<<"Item_base Destructor"<<endl;}   
    protected:    
    string book;     
    int number;    
};


#include <iostream>   
using namespace std;
#include <vector>
#include "Item_base.h"
int main (int argc, char * const argv[]) {    
    // insert code here...    
    vector<Item_base> vecbase;     
    Item_base derivo("Harry Potter",10);     
    cout<<"enter book name, qty, dqty"<<endl;     
    vecbase.push_back(derivo);     
    return 0;   
}

我收到的错误消息是:

error: no matching function for call to 'Item_base::Item_base(const Item_base&)'

有人可以帮我解决这个问题吗?我是编程新手

最佳答案

Vector只有两个push_back函数的实现

  • push_back(const T&)
  • push_back(T&&) (自 C++11 起)

这解释了为什么我们需要为我们的类提供带有参数 const T& 的复制构造函数

关于c++ - "no matching function"在自定义类型上使用push_back时调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12880992/

相关文章:

c++ - 我们可以像 C 中的结构一样使用 C++ 中的类吗?

指针 vector 中的 C++ 垃圾值

c++ - 如何将 vector<pair<string, int>> 中的字符串复制到 vector<string>?

c++ - 对 Vector 元素的 push_back 操作 (C++)

c++ - vector push_back 不起作用 c++

c++ - 通过 std::unique_ptr 使用 std::map 访问运算符 [] 的正确语法

python - QGraphicsScene 中的视觉像素完美选择

c++ - C/C++ MultiMap 库

c++ - 没有在C++枚举上命名的类型

C++ push_back 编译器错误“