没有对构造函数的匹配函数调用

no matching function call to a constructor

本文关键字:函数调用 构造函数      更新时间:2023-10-16
#include <iostream>
using namespace std;
template<class T>
class people{
    public:
    virtual void insert(T item)=0;
    virtual T show()=0;
};
class name
{
    private:
     string fname;
     string lname;
     public:
      name(string first, string last);
    //  bool operator== (name & p1, name &p2)
};
name::name(string first, string last){
    fname = first;
    lname = last;
}
template <class T>
class person : public people<T>
{
    private:
    T a[1];
    int size;
    public:
    person();
    virtual void insert(T info);
    virtual T show();
};
template<class T>
person<T>::person(){
    size = 0;
}
template<class T>
void person<T>::insert(T info){
    a[0] =info;
}
template <class T>
T person<T>::show(){
      return a[0];
}
int main(){
    string first("Julia"), last("Robert");
    name temp(first,last);
    people<name>* aPerson = new person<name>();
    aPerson-> insert(temp);
    cout << aPerson->show() << endl;
    return 0;
}

这些是我遇到的错误:

test.cpp: In function 'int main()':
test.cpp:53: error: no match for 'operator<<' in 'std::cout << people<T>::show [with T = name]()'
test.cpp: In constructor 'person<T>::person() [with T = name]':
test.cpp:51:   instantiated from here
test.cpp:37: error: no matching function for call to 'name::name()'
test.cpp:21: note: candidates are: name::name(std::string, std::string)
test.cpp:12: note:                 name::name(const name&)
name没有

默认构造函数,因此无法使用new person<name>初始化它。解决此问题的最简单方法是为 name 添加一个默认构造函数:

name() { }; //add this to name under public: of course

问题 2:您没有在名义上重载 << 运算符:下面是一个基本示例:

friend std::ostream& operator<<(std::ostream& stream, const name &nm); //Inside name class
std::ostream& operator<<(std::ostream& stream, const name &nm){ //OUTSIDE of name
    stream << nm.fname << " " << nm.lname << std::endl;
    return stream;
}