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. So i move it to inside my class
开发者_StackOverflow中文版 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++.
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. 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. 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. 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. The reason being is that the constructor runs before "main" (in a non-deterministic order with all the other global objects). 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:
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;
}
精彩评论