将类静态成员定义放入cpp文件中-技术限制? [英] Putting class static members definition into cpp file -- technical limitation?

查看:76
本文介绍了将类静态成员定义放入cpp文件中-技术限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中进行编码时,最喜欢的烦恼之一是在类中声明了一些静态变量,然后查看关于未解析的静态变量的编译错误(在以前,我总是很害怕,这是什么意思。) / p>

我的意思是经典示例,例如:



Test.h

 类测试
{
private:
static int m_staticVar;
int m_var;
}

Test.cpp

  int测试:: m_staticVar; 

这个定义令我感到更困惑的是,您不能使用这里的静态一词(因为在cpp中使用时,静态有不同的含义,请叹口气),所以您一无所知(除了静态成员vars这样的知识),为什么在地球上这样定义了Test类的一些int以及为什么m_var不是。



据您所知/为什么?我只能想到一个原因,这使链接器的工作变得更轻松-即出于同样的原因,您不能使用非整数常量(SomeClass m_var = something)。但是我不喜欢弯曲语言功能的想法,只是因为编译链的某些部分会很难吃掉它……

解决方案

嗯,这就是它的工作方式。您只在.h文件中声明了静态成员。链接器必须能够在链接到的目标文件中找到该静态成员的一个定义。您不能将定义放入.h文件中,因为它会生成多个定义。



更新:C ++ 17可以使用内联变量


one of my "favorite" annoyance when coding in C++ is declaring some static variable in my class and then looking at compilation error about unresolved static variable (in earlier times, I was always scared as hell what does it mean).

I mean classic example like:

Test.h

class Test
{
private:
  static int m_staticVar;
  int m_var;
}

Test.cpp

int Test::m_staticVar;

What makes it in my eyes even more confusing is the syntax of this definition, you can't use 'static' word here (as static has different meaning when used in cpp, sigh) so you have no idea (except the knowledge static member vars work like that) why on earth there's some int from Test class defined in this way and why m_var isn't.

To your knowledge / opinion, why is that? I can think of only one reason and that is making linker life easier -- i.e. for the same reason why you can't use non-integral constants (SomeClass m_var = something). But I don't like an idea of bending language features just because some part of compilation chain would have hard time eating it...

解决方案

Well, this is just the way it works. You've only declared the static member in the .h file. The linker needs to be able to find exactly one definition of that static member in the object files it links together. You can't put the definition in the .h file, that would generate multiple definitions.

UPDATE: C++17 can solve this with an inline variable.

这篇关于将类静态成员定义放入cpp文件中-技术限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆