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

时间:2013-11-09 19:05:51

标签: c++ c++11 constructor

#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&)

1 个答案:

答案 0 :(得分:2)

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