2016-10-08 2 views
0

Я знаю, что этот вопрос задан раньше, но, пожалуйста, наденьте меня. У меня возникли проблемы с пониманием того, как инициализировать класс.ошибка: нет соответствующего конструктора для инициализации

Вот код, о котором идет речь.

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

//------------------------------------------------------------------- --------------------------- 

class Date                 //Class Date 
{ 
public: 
    int day; 
    int month; 
    int year; 
    Date(); 
    Date(int,int,int); 
    ~Date(void); 
}; 

Date::Date(void) 
{ 
    day = 0; 
    month = 0; 
    year = 0; 
} 

Date::Date(int month, int day, int year) 
{ 
    day = day; 
    month = month; 
    year = year; 
}                   //Class Date 

//--------------------------------------------------------------------------------------------- 
                    //Class Book 
class Book 
{ 
public: 
    string _title; 
    string _author; 
    Date _published; 
    string _publisher; 
    float _price; 
    string _isbn; 
    int _page; 
    int _copies; 
    Book(); 
    Book(string,string,Date,string,float,string,int,int); 
    ~Book(void); 
}; 

Book::Book(void) 
{ 
    _title = ""; 
    _author = ""; 
    //_published; 
    _publisher = ""; 
    _price = 0; 
    _isbn = ""; 
    _page = 0; 
    _copies = 0; 

} 

Book::Book(string title, string author, Date published, string publisher, float price, string isbn, int page, int copies) 
{ 
    _title = title; 
    _author = author; 
    _published = published; 
    _publisher = publisher; 
    _price = price; 
    _isbn = isbn; 
    _page = page; 
    _copies = copies; 
}                   //Class Book 

//--------------------------------------------------------------------------------------------- 

class Node                //Class Node 
{ 
    friend class LinkedList; 
private: 
    Book *_book; 
    Node *_next; 
public: 
    Node(void); 
    Node(Book*); 
    Node(Book*,Node*); 
    ~Node(void); 
}; 

Node::Node(void) 
{ 
    _book = NULL; 
    _next = NULL; 
} 

Node::Node(Book *book) 
{ 
    _book = book; 
    _next = NULL; 
} 

Node::Node(Book *book, Node *next) 
{ 
    _book = book; 
    _next = next; 
}                  //Class Node 

//--------------------------------------------------------------------------------------------- 

class LinkedList              //Class LinkedList 
{ 
private: 
    Node *_head; 
    Node *_tail; 
public: 
    LinkedList(void); 
    LinkedList(Book*); 
    ~LinkedList(void); 
    void insert_front(Book*); 
    void insert_rear(Book*); 
    void print_list(void); 
}; 

LinkedList::LinkedList(void) 
{ 
    _head = NULL; 
    _tail = NULL; 
} 


LinkedList::LinkedList(Book *book) 
{ 
    _head = new Node(book); 
    _tail = _head; 
}                  //Class LinkedList 

//--------------------------------------------------------------------------------------------- 

void LinkedList::insert_front(Book *book) 
{ 
    if(_head == NULL) 
    { 
     _head = new Node(book); 
     _tail = _head; 
    } 
    else 
     _head = new Node(book, _head); 
} 

void LinkedList::insert_rear(Book *book) 
{ 
    if(_head == NULL) 
    { 
     _head = new Node(book); 
     _tail = _head; 
    } 
    else 
    { 
     _tail -> _next = new Node(book); 
     _tail = _tail -> _next; 
    } 
} 

void LinkedList::print_list(void) 
{ 
    Node *temp = _head; 
    while(temp!= NULL) 
    { 
     cout << temp -> _book -> _title << endl; 
     cout << temp -> _book -> _author << endl; 
     cout << temp -> _book -> _publisher << endl; 
     temp = temp -> _next; 
     cout << endl; 
    } 
} 

LinkedList::~LinkedList(void) 
{ 

} 

//--------------------------------------------------------------------------------------------- 
                //Main 
int main(void) 
{ 
    LinkedList myList; 
    ifstream myFile("input.txt"); 

    string title; 
    string author; 
    Date published;   // was "Date published(int,int,int);" 
    string publisher; 
    float price; 
    string isbn; 
    int page; 
    int copies; 

    while(myFile) 
    { 
     getline(myFile,title); 
     getline(myFile,author); 
     //getline(myFile,published); 
     getline(myFile,publisher); 
     //getline(myFile,price); 
     getline(myFile,isbn); 
     //getline(myFile,page); 
     //getline(myFile,copies); 

     myList.insert_front(new  Book(title,author,published,publisher,price,isbn,page,copies)); 
    } 

    myList.print_list(); 

    return 0; 
} 

Там ошибка Я интересует:

assignment3.cpp:213:33: error: no matching constructor for initialization of 
     'Book' 
    ...Book(title,author,published,publisher,price,isbn,page,copies)); 
    ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
assignment3.cpp:67:7: note: candidate constructor not viable: no known 
     conversion from 'Date (int, int, int)' to 'Date' for 3rd argument 
Book::Book(string title, string author, Date published, string publis... 
    ^
assignment3.cpp:38:7: note: candidate constructor (the implicit copy 
     constructor) not viable: requires 1 argument, but 8 were provided 
class Book 
    ^
assignment3.cpp:54:7: note: candidate constructor not viable: requires 0 
     arguments, but 8 were provided 
Book::Book(void) 
    ^
1 error generated.

Я сделал изменения предложил и теперь я получаю другую ошибку:

Undefined symbols for architecture x86_64: 
    "Date::~Date()", referenced from: 
     Book::Book() in assignment3-0f3b1c.o 
     Book::Book(std::__1::basic_string, std::__1::allocator >, std::__1::basic_string, std::__1::allocator >, Date, std::__1::basic_string, std::__1::allocator >, float, std::__1::basic_string, std::__1::allocator >, int, int) in assignment3-0f3b1c.o 
     _main in assignment3-0f3b1c.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation)
+0

Теперь вызывается ошибка при отсутствующем определении деструктора для класса 'Date'. Где это? Такая же проблема с классом 'Book' и' Node'. Если вы объявляете деструкторов, вы также должны их определять. – AnT

+0

@Hans Passant: класс 'Date' не нуждается в пользовательском конструкторе копирования - он не управляет не-неглубокими ресурсами. Просто потому, что что-то передается по значению, не означает, что ему нужен пользовательский конструктор копирования. Напротив, основная цель правила 3 ​​состоит в том, чтобы поощрять проекты, которые работают правильно с семантикой копирования, предоставленной компилятором. В этом случае копирование, предоставленное компилятором, вполне достаточно для класса «Дата», не нужно ничего делать. – AnT

+0

Как определить деструкторы? –

ответ

0

Ниже приводится объявление функции (published , занимает 3 int с, возвращается Date):

Date published(int,int,int) 

Вы хотите создать переменный:

Date published; 

или, если вы хотите, чтобы показать явно, что вы заботитесь о нулевой intialization:

Date published{}; 
Смежные вопросы