我创建了一个名为 Client 的类,定义如下 client.h:
#ifndef __CLIENT_H__
#define __CLIENT_H__
#include <string>
using namespace std;
class Client {
public:
Client(string n, string p) : name(n), password(p) {logged_in = true;}
void set_name(string n, string p) {name=n; password=p; }
private:
string name;
string password;
bool logged_in;
};
#endif
然后我在 admin.h 中从名为 Admin 的客户端继承了一个单例类:
#ifndef __ADMIN_H__
#define __ADMIN_H__
#include "client.h"
using namespace std;
class Admin : public Client {
public:
static Admin* get_admin(string n, string p)
{
if (Admin::n == 0)
Admin::admin = new Admin(n, p);
else
Admin::admin->set_name(n, p);
return Admin::admin;
}
private:
Admin(string n, string p) : Client(n, p) {Admin::n++;}
static int n;
static Admin* admin;
};
int Admin::n = 0;
#endif
这是我的 main.cpp:
#include <iostream>
#include <string>
#include "client.h"
#include "admin.h"
using namespace std;
int main()
{
Admin* administrator = Admin::get_admin("ghamar", "utcom90");
}
问题是,当我想使用 g++ (g++ main.cpp) 编译 main.cpp 时,出现以下错误:
/tmp/cc15VnHc.o: In function `Admin::get_admin(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
main.cpp:(.text._ZN5Admin9get_adminESsSs[Admin::get_admin(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)]+0x5f): undefined reference to `Admin::admin'
main.cpp:(.text._ZN5Admin9get_adminESsSs[Admin::get_admin(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)]+0xa0): undefined reference to `Admin::admin'
main.cpp:(.text._ZN5Admin9get_adminESsSs[Admin::get_admin(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)]+0xd1): undefined reference to `Admin::admin'
错误的重要部分说:
undefined reference to 'Admin::admin'
有人可以帮我解决这个问题吗?非常感谢您的时间。