You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++/CLI定义字符串literal成员报cannot be a literal data member错误如何解决

问题根源

C++/CLI 中 literal 关键字用于声明符合.NET规范的编译时常量,仅支持两类类型:

  • .NET 基元值类型(即你之前正常使用的int、unsigned short等类型)
  • 托管字符串类型 System::String^

你代码中使用的char*、const char*、std::string都属于原生C++非托管类型,无法被编译为.NET元数据可直接识别的常量,因此编译器会抛出禁止作为literal成员的错误。

解决方案

将类型替换为托管字符串String^,同时在字符串字面量前加L声明为宽字符格式,适配托管字符串的编码要求,正确写法如下:

using namespace System;

namespace TestNamespace
{
    static ref class TestClass
    {
        literal String^ TestString = L"fish";
    };
}
补充说明
  • 上述定义的字符串常量可以直接在C#项目中正常访问,用法和你之前使用值类型literal成员完全一致。
  • 除System::String^外,其他所有引用类型都不允许声明为literal成员。

内容的提问来源于stack exchange,提问作者JJtheJJpro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:36:07