如何在cpp文件中调用静态成员函数
我想知道是否可以在 cpp 文件中调用静态成员函数,如下所示:
Ah
class A
{
public:
A(){}
virtual ~A(){}
static void Initialize(){ g_pSomeType = new SomeType();}
private:
static SomeType* g_pSomeType;
};
A.cpp
#include "A.h"
SomeType* A::g_pSomeType = nullptr;
A::Initialize(); //here I get an error: "Initialize may not be redeclared outside of it's class"
是否可以执行这样的操作?这样我就能够初始化类的 .cpp 文件内的静态成员,以避免用户必须先调用initialize()?我想我可以找到一种方法来解决这个问题,但我很好奇是否有办法让它发挥作用。谢谢。
I'm wondering if I can call a static member function inside a cpp file like the following:
A.h
class A
{
public:
A(){}
virtual ~A(){}
static void Initialize(){ g_pSomeType = new SomeType();}
private:
static SomeType* g_pSomeType;
};
A.cpp
#include "A.h"
SomeType* A::g_pSomeType = nullptr;
A::Initialize(); //here I get an error: "Initialize may not be redeclared outside of it's class"
Is it possible to do something like this? So that I would be able to initialize the static members inside the .cpp file of the class, to avoid users from having to call initialize() first? I suppose I could find a way to work around this problem but I'm curious if there's a way to let this work. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在函数体之外编写任何可执行代码。仅当您位于函数或方法内部时,才可以调用
A::Initialize()
(或执行任何其他函数/方法调用)...编译器认为您再次声明
A::Initialize()
而不是调用它。You cannot write any executable code outside a function body. You can only call
A::Initialize()
(or do any other function/method call) only if you're inside a function or a method...The compiler thinks that you're declaring
A::Initialize()
again rather than calling it.您可以从构造函数中调用
initialize()
(也许之前没有调用过它)。You can call
initialize()
from the constructor (perhaps if it has not been called before).