I have a static link library project A, which contains files MyClass.h
and MyClass.cpp
. It defines a class and I want to use static member variables in the constructor. I have defined another project B to test this static link library and found that using the value of static member variables in the constructor and initializing the value of static member variables outside the class. If it is an int type, this value is initialized and accessible, but if it is a std: string or other non primitive type, the value does not exist. Why is this happening. Here are project A MyClass.h:
A MyClass.h:
#pragma once
#include <string>
#include <iostream>
class MyClass
{
public:
MyClass();
~MyClass() = default;
static const int myNumber;
static const std::string myString;
};
A MyClass.cpp
#include "MyClass.h"
const int MyClass::myNumber = 20;
const std::string MyClass::myString = "hello";
MyClass::MyClass()
{
std::cout << myNumber << "n";
std::cout << myString << "n";
}
B main.cpp
#include "../Project4/MyClass.h"
MyClass a;
int main()
{
}
but local var is correct:
#include "../Project4/MyClass.h"
int main()
{
MyClass a;
}
If we don’t use singleton mode, are there any other solutions
1