如何在cpp文件中调用静态成员函数

发布于 2024-12-24 21:03:58 字数 550 浏览 1 评论 0原文

我想知道是否可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮世清欢 2024-12-31 21:03:58

您不能在函数体之外编写任何可执行代码。仅当您位于函数或方法内部时,才可以调用 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.

顾忌 2024-12-31 21:03:58

您可以从构造函数中调用 initialize() (也许之前没有调用过它)。

You can call initialize() from the constructor (perhaps if it has not been called before).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文