簡體   English   中英

使用標頭中的構造函數初始化類

[英]Initialize a class with constructor inside a header

我有這個錯誤。 我的標題:

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

編譯器抱怨libtorrent :: fingerprint已經在另一個類中定義了,因為已經包含了它。 所以我將其移至班級內部

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

但是后來我的編譯器在那條移動的行上遇到了非常奇怪的錯誤,例如

error C2059: syntax error : 'string'

我做錯了什么?

您不能在C ++中執行此操作。

如果你想的實例libtorrent::fingerprint稱為a (可怕的名字),那么你需要將其申報為類的屬性,並在構造函數初始化它。 這是一個例子:

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

private:
    libtorrent::fingerprint a
};

error C2059: syntax error : 'string'

這與您發布的代碼無關。

在您的.h文件中。 聲明此:

#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

在您的.cpp(.cc)文件中。 定義對象:

#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.
}

另外,在我們的團隊中,我們明確禁止使用“全局對象”,例如您聲明的“ a”實例。 原因是構造函數在“ main”之前運行(與所有其他全局對象以不確定的順序運行)。 而且它的析構函數直到主出口退出后才運行。

如果您確實需要全局使用“ 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