字面量与常量变量在C ++ / CLI中 [英] Literal field versus constant variable in C++/CLI

查看:132
本文介绍了字面量与常量变量在C ++ / CLI中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

literal int inchesPerFoot = 12;

这是一个常数,因为const FIELD 因为一个字段不能初始化自身...所以:

  class aClass 
{
private:
const int aConstant = 1; //语法错误。
...
};

感谢,



Scott

解决方案

字面值用于编译时常量。它与类相关联(类似于静态const字段)。在你的例子中 aConstant 是一个非静态的const(一个基于实例的)字段 - 这就是为什么你不能在声明的时候初始化它(它将被初始化在ctor的初始化列表中)。



字面值和静态const字段之间的区别是,引用组件不能使用静态const字段作为编译时常量,而文字可以。但是,在同一个程序集中,static const可以用作编译时常量。



FYI,
literal相当于C#的const。
initonly等效于C#的readonly。


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

解决方案

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.

这篇关于字面量与常量变量在C ++ / CLI中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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