Accessing to a static variable from the same class
Hi,
I'm implementing a class to do operations with a SQLite database and I have this header file
Code:
...
class ObjectDatabase{
public:
static bool createTables();
static void closeDatabase();
static bool vacuumDatabase();
protected:
static void setErrorString
(QString);
private:
};
...
But when I try to access from this functions to the var m_errorString the compiler say that the var isn't defined.
What can be the problem?
Thank's
Re: Accessing to a static variable from the same class
I don't see an error in the code you posted. That means that the error is somewhere else. A typo, perhaps? Maybe your function definition doesn't have "ObjectDatabase::" in front of the name?
If that doesn't help, could you copy/paste the code where you try to access the variable?
Re: Accessing to a static variable from the same class
Define the static variable in the .cpp file:
Code:
QString ObjectDatabase
::m_errorString;
Re: Accessing to a static variable from the same class
Oh, you're right. I admit I've never used static variables in C++ in that way. How silly.
Re: Accessing to a static variable from the same class
So the code that works is this:
objectdatabase.h
Code:
...
class ObjectDatabase{
public:
static bool createTables();
static void closeDatabase();
static bool vacuumDatabase();
protected:
static void setErrorString
(QString);
private:
};
...
objectdatabase.cpp
Code:
...
QString ObjectDatabase
::m_errorString;
...
void ObjectDatabase
::setErrorString(QString string
){ m_errorString=string;
}
...
Thanks to all
Re: Accessing to a static variable from the same class
Now we could start a discussion, whether the whole static stuff is good design, or if it is better be done as a singleton. Classes with nothing else but static methods and static members always make me a bit nervous. ;)
Re: Accessing to a static variable from the same class
You can always convert such class to a namespace with functions and global objects if you don't like a static class :]