I’ve written a template Link list, but when I try to add an object to it I get the error “C2512 ‘Customer’: No Appropriate default constructor available” thrown from the node constructor.
Code:
#pragma once
#include <iostream>
using namespace std;
template <class T>
class node;
template <class T>
class l_list
{
public:
l_list() { head = tail = NULL; }
~l_list();
void add(T &obj);
T remove(int ID);
void print(ostream &out);
private:
node<T> *head, *tail;
};
template <class T>
class node
{
public:
template<class> friend class l_list;
node() {next = NULL;}
private:
T data;
node *next;
};
template <class T>
l_list<T>::~l_list()
{
}
template <class T>
void l_list<T>::add(T &obj)
{
node<T> *ptr = new node<T>;
ptr -> data = obj;
ptr -> next = head;
head = ptr;
if (tail == NULL) {tail = ptr;}
}
template <class T>
T l_list<T>::remove(int ID)
{
int i = 0;
node<T> * ptr = head;
while (ptr -> data -> id != ID)
{
ptr = ptr -> next;
}
}
template <class T>
void l_list<T>::print(ostream &out)
{
int i = 0;
node<T> *ptr = head;
while ( ptr != NULL )
{
out << ptr -> data << endl;
ptr = ptr -> next;
i++;
}
}
and the object that I try and put in the list
l_list<Customer> customers;
Customer bob("Bob", "25 Bob Lane", "01bob82", "M", "bob/bob/bob");
customers.add(bob);
edit to add Customer:
#pragma once
#include "l_list.h"
#include "Account.h"
#include <string>
using namespace std;
class Customer
{
private:
l_list<Account> accounts;
string name;
string address;
string telNo;
string sex;
string dob;
public:
Customer(string name, string address, string telNo, string sex, string dob)
{
Customer::name = name;
Customer::address = address;
Customer::telNo = telNo;
Customer::sex = sex;
Customer::dob = dob;
}
void createAccount()
{
cout << "What type of account?";
}
~Customer()
{
}
};
This line:
Is trying to default-construct a
Twithinnode. Since there is no default constructor, no compiley =PYou can address this by using the copy constructor (which you define or use the default one , so long as
Tproperly complies with The Rule of Three) or by defining a default constructor forT. I prefer the former if I want to harden construct access toTOf course, you need to define a proper constructor for
node<T>::node(const T&)Been a slow morning so sorry if I messed something up in there. =P