visual如何在托管C++类中为静态变量赋值

visual How can I give a value to a static variable in a managed C++ class?

本文关键字:静态 变量 赋值 C++ visual      更新时间:2023-10-16

在VC++CLR项目中,我有一个类temp。我正在尝试将静态变量temp1设置为5。

我得到一个编译错误:

错误32错误LNK2020:未解析的令牌(0A0005FB)";公用:静态int temp::temp1";(?temp1@temp@@2HA)C:\Users\user100\Documents\VisualStudio 2012\NewProject 32位\从数据创建最小条形图2\create最小数据条形图\从数据创建最小条形图5.obj

错误33错误LNK2001:未解析的外部符号";public:静态inttemp::temp1";(?temp1@temp@@2HA)C:\Users\user100\Documents\VisualStudio 2012\NewProject 32位\从数据创建最小条形图2\create最小数据条形图\从数据创建最小条形图5.obj

我该怎么修?

class temp
{
    public:
    static int temp1;
};
int main(array<System::String ^> ^args)
{
    temp::temp1 = 5;
}

在类中声明静态变量时,实际上不会创建内存。你需要一个单独的变量callout来为它创建RAM。这就是编译器告诉你的。

//Outside your class declaration:
int temp::temp1;

定义静态成员变量:

class temp
{
    public:
        static int temp1;
};
int temp::temp1 = 0;
// Fixed main() ;)
int main(int argc, char** argv)
{
        temp::temp1 = 5;
        return 0;
}