Literal field versus constant variable in C++/CLI

笑着哭i 提交于 2019-12-23 10:09:19

问题


I'm going over some C++/CLI material and I've come across the concept of a literal field:

literal int inchesPerFoot = 12;

Is this preferable to a const because a const FIELD can't exist because a field cannot initialize itself...so:

class aClass
{
    private:
        const int aConstant = 1;    // Syntax error.
...
};

Thanks,

Scott


回答1:


A literal field is used for compile-time constants. It is associated with the class (similar to a "static const" field). In your example aConstant is a non-static const (an instance based) field--which is why you can't initialize it at the time of declaration (it would be initialized in the ctor's initialization list).

The difference between literal and static const fields is that referencing assemblies cannot use static const fields as compile-time constants, while literals can. However, within the same assembly, static const can be used as compile time constants.

FYI, literal is equivalent to C#'s const. initonly is equivalent to C#'s readonly.



来源:https://stackoverflow.com/questions/5238078/literal-field-versus-constant-variable-in-c-cli

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