简体   繁体   English

在CLI C中作为全局not const变量的库类

[英]Class as library of global not const variables in cli c++

How should defined class where are only global variables? 应该如何定义类,而只有全局变量呢? I did something like that: 我做了这样的事情:

public ref class Klient
{
public:
    Klient(){}
    // zmienne
    static array<DWORD,2>^ klienty = gcnew array<DWORD,2>(40,2);
    static int i = 0;
    static DWORD pid;
    static HANDLE handle;
    static String^ nick;
    //funkcje
};

But if i include it more than 1 time it won't compile and showing redefinition of class error. 但是,如果我添加它超过1次,它将无法编译并显示对类错误的重新定义。

Did you guard your header? 你保护好头了吗? In Visual Studio, you should place this directive at the top of all header files: 在Visual Studio中,应将此指令放在所有头文件的顶部:

#pragma once

This is equivalent to the classic C++ header guard: 这等效于经典的C ++标头保护:

#ifndef HEADER_SYMBOL_X
#define HEADER_SYMBOL_X

 // class declarations go here

#endif // HEADER_SYMBOL_X

If you don't guard your header, C++/CLI will indeed try to redefine your class on each include. 如果您不保护标题,则C ++ / CLI实际上将尝试在每个include上重新定义您的类。

You'll have to be a little more clear, and paste the error you get. 您必须更加清楚一些,然后粘贴您得到的错误。 Also if you have a "ref" class the compiler generates a default constructor for you, so you don't need to write one. 同样,如果您有“ ref”类,则编译器会为您生成一个默认构造函数,因此您无需编写一个构造函数。

This code worked for me, I was able to fetch the static int value into my WPF application: 这段代码对我有用,我能够将静态int值提取到WPF应用程序中:

#pragma once

#include "windows.h"

using namespace System;

namespace cppcli 
{
    public ref class Klient
    {
        public:
            static array<DWORD,2>^ klienty = gcnew array<DWORD,2>(40,2);
            static int i = 22;
            static DWORD pid;
            static HANDLE handle;
            static String^ nick;
    };
}

Update: 更新:
Noticed your comment, yes you need #pragma once in there. 注意到您的评论,是的,您需要在其中输入#pragma once I assumed it was there since it's generated automatically by Visual Studio, well good to know that it works :-) 我以为它在那里,因为它是由Visual Studio自动生成的,很高兴知道它可以工作:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM