C ++:单例类设计(错误:未解析的外部符号)

时间:2017-03-30 08:16:46

标签: c++ compiler-errors static singleton linker-errors

我在Visual Studio上为C ++项目实现单例类设计。它基于GitHub code sample。逻辑方面,我的代码似乎是正确的,但我的编译器出错了。有谁知道什么是错的?

我有几个单身人士课程。这是其中一个的代码示例。

AccountBG.h

#ifndef ACCOUNTBG_H
#define ACCOUNTBG_H

#include "Lecturer.h"
#include "Student.h"
#include "Type.h"

class AccountBG
{
public:
   static AccountBG* getInstance();
   // GET Methods
   Lecturer* getLecturer();
   Student* getStudent();
   // SET Methods
   void setLecturer(int, string);
   void setStudent(int, string);
private:
   // Singleton class instance
   static AccountBG* instance;
   AccountBG(); // Private constructor to prevent instancing.
   Lecturer *lecturer;
   Student *student;
};

#endif // !ACCOUNTBG_H

AccountBG.cpp

#include "AccountBG.h"
// Null, because instance will be initialized on demand.
AccountBG* AccountBG::instance = 0;

AccountBG* AccountBG::getInstance() {
    if (instance == 0) {
        instance = new AccountBG();
    }
    return instance;
}

// GET Methods
Lecturer* AccountBG::getLecturer() {
    return this->lecturer;
}

Student* AccountBG::getStudent() {
    return this->student;
}

// SET Methods
void AccountBG::setLecturer(int id, string username) {
    this->lecturer = new Lecturer();
    this->lecturer->setID(id);
    this->lecturer->setUsername(username);
    this->lecturer->setType("Lecturer");
}

void AccountBG::setStudent(int id, string username) {
    this->student = new Student();
    this->student->setID(id);
    this->student->setUsername(username);
    this->student->setType("Student");
}

编译器错误的屏幕截图

Errors as seen on VS2015

1 个答案:

答案 0 :(得分:1)

未解析的外部符号通常是通过调用已声明但未实现的函数引起的。

在您的情况下,您不会实现AccountBG的构造函数,只会声明。

其他功能可能存在同样的问题:

MarkingData::instance()
Quiz::Quiz()
QuizTracker::QuizTracker()

为这些功能添加实现可以解决您的问题。