[英]Why can't I initialize non-const static member or static array in class?
[英]Why can't I define a static class member field in .hpp?
class TestClass
{
public:
static int testMember;
template<class T> static T* Foo()
{
//Defination....
}
}
//int TestClass::testMember; //Duplicate definition
为什么我不能在.hpp中定义成员字段,而我可以在.hpp中定义成员函数?
是否必须在 a.cpp 文件中定义?
为什么我不能在.hpp中定义成员字段
你可以。
C++ 不关心文件的名称,也不关心文件的扩展名。
你不能做的是多次定义变量。 这显然违反了单一定义规则。
为了满足单一定义规则,您有两种选择:
在 C++17 或更高版本中,使变量inline
。
class TestClass { public: static inline int testMember; template<class T> static T* Foo() { //Defination.... } }
在 C++ 的任何版本中,将定义放在代码中将被编译一次的位置。
为什么... [可以] 在.hpp 中定义成员函数吗?
因为在 class 中定义的成员函数是隐式inline
。 就像你的变量可能一样。
正如 Drew Dormann 所提到的,模板成员函数(静态或非静态)是隐式内联的。
class 模板也是如此:
template <typename>
class TestClass
{
public:
static int testMember;
template<class T> static T* Foo()
{
//Definition....
}
};
// prior to C++17 you definition MUST be outside the class in the header
template <typename T>
int TestClass<T>::testMember{};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.