简体   繁体   English

使用标头中的构造函数初始化类

[英]Initialize a class with constructor inside a header

i´m having this error. 我有这个错误。 My header: 我的标题:

libtorrent::fingerprint a("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0);
class TorrentClass
{
}

The compiler complains that libtorrent::fingerprint a already defined in another class, because it has been inclused. 编译器抱怨libtorrent :: fingerprint已经在另一个类中定义了,因为已经包含了它。 So i move it to inside my class 所以我将其移至班级内部

    class TorrentClass
    {
           private:
           libtorrent::fingerprint a("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0);
    }

But then my compiler get very strange errors over that moved line, like 但是后来我的编译器在那条移动的行上遇到了非常奇怪的错误,例如

error C2059: syntax error : 'string'

What i´m doing wrong ? 我做错了什么?

You cannot do this in C++. 您不能在C ++中执行此操作。

If you want an instance of libtorrent::fingerprint called a (terrible name) then you will need to declare it as an attribute of the class and initialise it in a constructor. 如果你想的实例libtorrent::fingerprint称为a (可怕的名字),那么你需要将其申报为类的属性,并在构造函数初始化它。 Here is an example: 这是一个例子:

class TorrentClass
{
public:
    TorrentClass()
        :a("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0)
    {
    }

private:
    libtorrent::fingerprint a
};

error C2059: syntax error : 'string'

This has nothing to do with the code that you posted. 这与您发布的代码无关。

In your .h file. 在您的.h文件中。 Declare this: 声明此:

#ifndef CLASS_TORRENT_H
#define CLASS_TORRENT_H
#include "libtorrent.h" // I'm guessing this is the header file that declares the "fingerprint" class
extern libtorrent::fingerprint a;
class TorrentClass
{
public:
   TorrentClass();
   // your class declaration goes here
};

#endif

In your .cpp (.cc) file. 在您的.cpp(.cc)文件中。 Define the objects: 定义对象:

#include "ClassTorrent.h" // the header file described above
libtorrent::fingerprint a("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0);
TorrentClass::TorrentClass()
{
  // your constructor code goes here.
}

Also, on my team, we explicitly disallow "global objects" such as the instance of "a" you have declared. 另外,在我们的团队中,我们明确禁止使用“全局对象”,例如您声明的“ a”实例。 The reason being is that the constructor runs before "main" (in a non-deterministic order with all the other global objects). 原因是构造函数在“ main”之前运行(与所有其他全局对象以不确定的顺序运行)。 And it's destructor doesn't run until after main exits. 而且它的析构函数直到主出口退出后才运行。

If you really need "a" to be global, instantiate it as a pointer and allocate it with new: 如果您确实需要全局使用“ a”,请将其实例化为指针并使用new分配它:

libtorrent::fingerprint *g_pFingerPrintA;
int main()
{
    g_pFingerPrintA = new libtorrent::fingerprint("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0);

    // program code goes here

    // shutdown
    delete g_pFingerPrintA;
}

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

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