没有指定初始化器的静态结构初始化?

Str*_*gos 1 c c++ static designated-initializer visual-studio-2017

以下指定初始值设定项示例在带有 /std:c++latest 的 Visual Studio 2019 中有效,但我想知道如何在 Visual Studio 2017 中没有指定初始值设定项的情况下完成相同的操作。

我正在使用 C++,我意识到有一种面向对象的方法可以做到这一点,但我并不是问如何使用构造函数在 C++ 中重新创建它。这使得这个问题的标签有点混乱,抱歉造成任何混乱。

我也在为这里的术语而苦苦挣扎。只是为了确认一下,是&(struct Foo)复合文字吗?这是实现编译时静态初始化吗?可以constexpr在这里用某种方式代替吗?

// Header
struct Foo
{
    void (*Bar)();
};

extern struct Foo *FooAPI;

// Source
static void Bar()
{

}

static struct Foo *FooAPI = &(struct Foo) { // Error: Expecting an expression
    .Bar = Bar
};
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 5

struct Foo
{
    void *(Bar)();
};
Run Code Online (Sandbox Code Playgroud)

Foo::Bar是一个返回 的成员函数void*。C 没有成员函数,因此这在 C 中是不正确的。

{
    .Bar = Bar;
}
Run Code Online (Sandbox Code Playgroud)

这在两种语言中都是不正确的。您不能在那里放置分号。解决办法:去掉分号。可以选择用逗号替换。

此外,Foo::Bar是一个成员函数,因此您无法为其提供初始化程序。您可能想要Foo::Bar成为一个返回 的函数的指针void。其语法为:

struct Foo
{
    void (*Bar)();
};
// or nicer way:
struct Foo
{
    using Fun = void();
    Fun* Bar;
};
Run Code Online (Sandbox Code Playgroud)
extern struct Foo *FooAPI;
static struct Foo *FooAPI =
Run Code Online (Sandbox Code Playgroud)

已声明的变量extern不得重新声明static。解决办法:删除static.

只是为了确认一下,是&(struct Foo)复合文字吗?

(struct Foo) { ... }是一个复合文字。在这种情况下,一元 & 是 addressof 运算符,复合文字是操作数。

没有指定初始化器的静态结构初始化?

只需删除指示符,以便初始化程序按其声明顺序应用于成员。如果初始化程序不在成员的声明顺序中,则必须重新排序初始化程序。在你的情况下:

{
    .Bar = Bar,
}
// becomes ->
{
    /*.Bar =*/ Bar,
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 C++

C++ 中没有复合文字。它们是 C 功能(自 C99 起)。

要在 C++ 中重写它,您需要使用命名变量:

static Foo foo {
    Bar,
};
Foo *FooAPI = &foo;
Run Code Online (Sandbox Code Playgroud)