C++/CLI, static constructor outside class declaration

▼魔方 西西 提交于 2019-12-12 10:33: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:


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



来源:https://stackoverflow.com/questions/3188164/c-cli-static-constructor-outside-class-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!