静态指针有什么问题?

What is the problem about static pointer?

我刚刚开始学习 OOP。我想创建一个 BookList 的 LinkList 并使用 Singleton 设计模式创建一个唯一的对象“库”来管理这个 BookList,但是初始化 BookList 时出现问题。

class Library {
public:
static Library* library;
static BookList* pHead;
static int i;
static int getNewID(BookType typ) {
    return i++;
}
static Library* getLibrary();
static Library* getLibrary(BookList*);
static BookList* getNull(BookList*);
private:
Library(BookList* a); 
};
Library* Library::getLibrary() {
if (library == NULL) {
        BookList* a = new BookList;
        library = new Library(a);
    }
    return library;
}
Library* Library::getLibrary(BookList* a) {
    if (library == NULL) {
        library = new Library(a);
    }
    return library;
}
Library::Library(BookList* a) {
    BookList* p = pHead;
    while (1) {
        if (p->getNext() == NULL) {  //I got error
        p->setNext(a);
        break;
        }
        p = p->getNext();
    }
}

我这里有一个错误:

Undefined symbols for architecture x86_64: "Library::pHead", referenced from: Library::Library(BookList*) in test-9c557d.o ld: symbol(s) not found for architecture x86_64

我是不是忘记了什么?

好像您没有定义 pHead - 您只是声明了它。尝试在您的实现文件 (.cpp / .cxx) 中添加以下代码:

BookList* Library::pHead = new BookList();