I have created the following test to try and implement a static method to expose a static variable that I am usually able to do in C# in 2 seconds. The concepts seem almost identical and I can create the static variable and methods with no computation error but when I attempt to access my static methods I receive:
You need to create the string Test::TestClass::connectionString somewhere.
static member variables don't get created when an instance of a class is. There's only one instance of the static var, and you have to create it somewhere.
If I take it outside the class I also end up exposing it. If I cannot use it within a class and set it to private. How could I go about hiding the actual variable and exposing access only via static method?
Declare it inside the class (in the header file) and define it outside the class (in the source file), just like you do with the functions.
TestClass.h
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <string>
namespace Test
{
class TestClass
{
private:
static std::string connectionString; // This is only a declaration.public:
staticvoid setConnectionString(std::string str);
static std::string getConnectionString();
};
}
TestClass.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "TestClass.h"
namespace Test
{
// Defines the static variable. This is where you initialize the variable.std::string TestClass::connectionString; void TestClass::setConnectionString(std::string str)
{
connectionString = str;
}
std::string TestClass::getConnectionString()
{
return connectionString;
}
}