编译器错误 C3894

“var”:initonly 静态数据成员的左值只能在类“class”的类构造函数中使用 l-value

静态 initonly 数据成员只能在声明时用作 l-value,或在静态构造函数中使用。

实例(非静态)initonly 数据成员只能在声明时用作 l-value,或者在实例(非静态)构造函数中使用。

下面的示例生成 C3894:

// C3894.cpp
// compile with: /clr
ref struct Y1 {
   initonly static int data_var = 0;

public:
   // class constructor
   static Y1() {
      data_var = 99;   // OK
      System::Console::WriteLine("in static constructor");
   }

   // not the class constructor
   Y1(int i) {
      data_var = i;   // C3894
   }

   static void Test() {}

};

int main() {
   Y1::data_var = 88;   // C3894
   int i = Y1::data_var;
   Y1 ^ MyY1 = gcnew Y1(99);
   Y1::Test();
}