C ++ / CLI,静态构造函数在类声明之外 [英] C++/CLI, static constructor outside class declaration

查看:198
本文介绍了C ++ / CLI,静态构造函数在类声明之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将托管类的静态构造函数的主体放在类声明之外?这种语法似乎是可编译的,但它是真的意味着静态构造函数,还是只是一个静态(=不可见的外部翻译单元)函数?

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() {}


推荐答案

是的,这是创建C ++ / CLI静态构造函数的正确语法。你可以知道它不创建一个静态函数,因为它不是一个有效的函数声明语法。函数必须指定返回类型。此外,编译器会抱怨 Foo()不是类Foo的成员,如果它没有链接到你在类定义中声明的构造函数。

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.

您可以使用命名空间System轻松地测试:

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");
}

这将输出:


静态构造函数

构造函数

主要

Static Constructor
Constructor
Main

这篇关于C ++ / CLI,静态构造函数在类声明之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆