2016-09-21 2 views
0

Возможно, это потому, что я смотрел на это в течение 5 часов подряд, и я просто просматриваю очевидное решение, но Xcode утверждает, что мой вектор объектов (объявленный в файле заголовка) не объявлен в одном .cpp файл; однако, мой другой .cpp-файл может получить доступ к вектору, поэтому я не уверен, в чем проблема. Может быть, мои заголовочные файлы неуместны, или я непреднамеренно «круговые ссылки»? Предложения, пожалуйста?Возможные круговые ссылки?

publications.h

#ifndef PUBLICATIONS_H 
#define PUBLICATIONS_H 

#include "std_lib_facilities.h" 

class Publication { 
    private: 
     string 
      publication_title, 
      publication_author, 
      publication_year, 
      publication_genre, 
      publication_media, 
      publication_target_age, 
      publication_ISBN; 

     bool currently_checked_out; 

    public: 
     Publication(string title, string author, string year, string genre, string media, string target_age, string ISBN, bool checked_out) { 
      publication_title = title; 
      publication_author = author; 
      publication_year = year; 
      publication_genre = genre; 
      publication_media = media; 
      publication_target_age = target_age; 
      publication_ISBN = ISBN; 
      currently_checked_out = checked_out; 
     } 

     Publication(){}; 

}; 
#endif /* PUBLICATIONS_H */ 

library.h

#ifndef LIBRARY_H 
#define LIBRARY_H 

#include "std_lib_facilities.h" 

class Publication; 

class Library { 
    private: 
     vector<Publication> lb; 

    public: 
     Library(){}; 

     void documentation(); 
     void list_all_publications(); 
     void new_publication(string title, string author, string year, string genre, string media, string target_age, string ISBN, bool currently_checked_out); 
}; 
#endif /* LIBRARY_H */ 

patron.h

#ifndef PATRON_H 
#define PATRON_H 

#include "std_lib_facilities.h" 

class Publication; 

class Patron { 
    private: 
     string 
      customer_name, 
      customer_telephone; 

    public: 

     void check_out_publication(string publication_requested); 
     void return_publication(string check_in_publication_name); 
     void check_out(); 
     bool is_checked_out(); 

     Patron(){}; 


}; 
#endif /* PATRON_H */ 

library.cpp (Отлично работает, вектор может доступа в library.h)

#include "library.h" 
#include "patron.h" 
#include "publications.h" 
#include "std_lib_facilities.h" 

Patron p; 

void Library::documentation() { 
    cout << "\n-----Create a new publication----\n"; 
    cout << "You will enter all the necessary info for a new publication (title, author, year, genre, media, target age, and ISBN).\n"; 

    cout << "\n----List all Publications-----\n"; 
    cout << "List all publications that have been entered (in this current session).\n"; 

    cout << "\n---Check out Publication----\n"; 
    cout << "You will enter your name and telephone number and the publication will be checked out.\n"; 

    cout << "\n-----Return Publication------\n"; 
    cout << "A previously checked out publication will be marked as returned.\n"; 
} 

void Library::new_publication(string title, string author, string year, string genre, string media, string target_age, string ISBN, bool checked_out) { 

    lb.push_back(Publication(title, author, year, genre, media, target_age, ISBN, checked_out)); 
} 

void Library::list_all_publications() { 
    for (int i = 0; i < lb.size(); i++) { 
     cout << "Title: " << "\tChecked Out: " << p.is_checked_out() << endl; 
    } 

} 

patron.cpp (проблемный файл, не может вектор доступа в library.h)

#include "publications.h" 
#include "library.h" 
#include "patron.h" 
#include "std_lib_facilities.h" 

void Patron::check_out_publication(string publication_requested) { 
    // check to make sure publication isn't already checked out. 

    for (int i = 0; i < lb.size(); i++) { 

     if ((publication_requested == lb[i].publication_title) && lb[i].currently_checked_out) { 
      cout << "Sorry, this publication is currently checked out." << endl; 

     } else if ((publication_requested == lb[i].publication_title) && !(lb[i].currently_checked_out)) { 
      cout << "Enter your name: "; 
      getline(cin, customer_name); 

      cout << "Enter your telephone number (no dashes/no spaces): "; 
      cin >> customer_telephone; 
     } else { 
      continue; 

     } 
    } 

} 

void Patron::return_publication(string check_in) { 
    for (int i = 0; i < lb.size(); i++) { 
     if ((check_in == lb[i].publication_title) && lb[i].currently_checked_out) { 
      // marked as no longer checked out. 
      lb[i].currently_checked_out = false; 
     } 
    } 
} 

bool Patron::is_checked_out() { 
    return currently_checked_out; 
} 

void Patron::check_out() { 
    currently_checked_out = true; 
} 

Ошибка в patron.cpp

USE OF UNDECLARED IDENTIFIER "lb" 
+0

'library.h' must' #include "publications.h" '. Поскольку у вас есть это сейчас, это неопределенное поведение (библиотека объявляет вектор неполного типа) –

+0

Ваше сообщение об ошибке не имеет ничего общего с включенными; в 'Patron :: check_out_publication' вы пишете' for (int i = 0; i

ответ

0

lb является частным членом класса Library. Вы можете получить к нему доступ в файле library.cpp, потому что используете его в функции члена Library. Если в классе Patron вы напрямую обращаетесь к нему. Но компилятор видит это как еще одну переменную, которую вы не объявили. Вероятно, вам нужно добавить аксессуар в Library.

+0

будет ли библиотека библиотеки работать в качестве аксессуара? Я новичок в C++, поэтому я все еще пытаюсь понять ... – David

+0

@David Нет, это просто создает переменную типа 'Library'. Все, что использует этот объект, не имеет прямого доступа к частным членам 'library'. Есть несколько веб-страниц, которые могут вам помочь. Попробуйте найти «C++ accessor». Поскольку это, вероятно, укусит вас, вы также захотите узнать разницу между возвращаемыми копиями данных и ссылками, поскольку C++ использует копии по умолчанию. –

+0

хорошо, спасибо за подсказку. – David

Смежные вопросы