C++/CLI, static constructor outside class declarat

2019-06-15 04:02发布

How do I put body of static constructor of a managed class outside class declaration? This syntax seems to be compilable, but does it really mean static constructor, or just a static (=not visible outside translation unit) function?

ref class Foo {
    static Foo();
}

static Foo::Foo() {}

1条回答
我只想做你的唯一
2楼-- · 2019-06-15 04:24

Yes, that is the correct syntax to create a C++/CLI static constructor. You can know its not creating a static function since that is not a valid function declaration syntax. Functions must have the return type specified. Also, the compiler would complain that Foo() is not a member of class Foo if it weren't linking it to the constructor you declared in the class definition.

You can test the fairly easily:

using namespace System;

ref class Foo {
    static Foo();
    Foo();
}

static Foo::Foo() { Console.WriteLine("Static Constructor"); }
Foo::Foo() { Console.WriteLine("Constructor"); }

int main(array<System::String ^> ^args)
{
    Foo ^f = gcnew Foo();
    Console.WriteLine("Main");
}

This would output:

Static Constructor
Constructor
Main

查看更多
登录 后发表回答