gpt4 book ai didi

c++ - cpp hpp分离

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:28:08 24 4
gpt4 key购买 nike

当我尝试将类的声明和定义放入单独的 hpp 和 cpp 文件时出现一些错误。你能帮我修一下吗?我正在尝试像这样操纵一个单例:

唱.hpp:

class GlobalClass {
int m_value;
static GlobalClass *s_instance;
GlobalClass(int);

public:
int get_value();
void set_value(int v);
static GlobalClass *instance(); };

唱.cpp:

#include"sing.hpp"
GlobalClass::GlobalClass(int v = 0)
{
this->m_value = v;
}

int GlobalClass::get_value()
{
return this->m_value;
}

void GlobalClass::set_value(int v)
{
this->m_value = v;
}

static GlobalClass GlobalClass::*instance()
{
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}

主要.cpp:

#include "sing.hpp"
int main()
{
GlobalClass *s=0;
}

命令和错误是:

~/workspace/singleton$ g++  main.cpp sing.cpp 
sing.cpp: In function ‘GlobalClass GlobalClass::* instance()’:
sing.cpp:19:10: error: ‘s_instance’ was not declared in this scope
sing.cpp:2:1: error: ‘GlobalClass::GlobalClass(int)’ is private
sing.cpp:20:23: error: within this context
sing.cpp:21:12: error: ‘s_instance’ was not declared in this scope

最佳答案

static GlobalClass GlobalClass::*instance()
{
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}

这个定义不应该有 static 标签。只有声明。

事实上,您实际上并没有定义成员函数;如果您提供了一个 s_instance 变量,您将然后得到关于它的错误。

* 也放错地方了。

您稍后还会收到关于 s_instance 的链接错误,因为您没有定义它。

关于c++ - cpp hpp分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9599716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com