Я следую онлайн-руководству, которое очень похоже на мой код, но не совсем то же самое. Я изменил его, чтобы лучше понимать, но у меня проблемы с получением / возвратом строкового значения из встроенной функции. Строковое значение становится пустым, как только компилятор выйдет из последней фигурной скобки Another.cpp
.
Есть ли способ решить мою проблему без изменения структуры моих файлов, а также кода? В частности, я не хочу ничего менять с Another.h
. Пожалуйста, если кто-то может объяснить, что может быть причиной встроенной функции здесь, он будет очень признателен.
Another.h
#pragma once
#include<iostream>
#include"Temple.h"
#include<memory>
namespace NamespaceAn
{
class Test
{
public:
static void Init();
inline static std::shared_ptr<Outside::Inside>& GetString() { return s_String; }
private:
static std::shared_ptr<Outside::Inside> s_String;
};
}
Другой. cpp
#include "Another.h"
#include<string>
namespace NamespaceAn
{
std::shared_ptr<Outside::Inside>Test::s_String;
void Test::Init()
{
//This s_String value is getting disapprear as soon as the compiler get out of the curly bracket
auto s_String = Outside::Inside("asdf");
//below all are commented out for the Another.cpp
//std::string Ast = "asdf";
/*std::string Ast = "asdf";
auto s_String = new Outside::Inside(Ast);*/
/*Outside::Inside* ob = new Outside::Inside(Ast);
auto s_String = &(ob->Get());*/
// ***** Attention ****
//no operator "=" matches the operands and binary '=' no operator found which takes a right-hand ooperand of type std::string*(no acceptable conversion)
//s_String = &(ob->Get());
//auto s_String = Ast;
//auto s_String = Outside::Inside("asdf");
//auto s_String = new Outside::Inside("asdf");
//s_String = reinterpret_cast<Ast>;
//*s_String = &(Outside::Inside("asdf"));
//s_String = reinterpret_cast<Outside::Inside*>(&Outside::Inside("asdf"));
}
}
Temple.h
#pragma once
#include <string>
namespace Outside
{
class Inside
{
std::string m_String = "tesi";
public:
Inside(std::string x)
{
m_String = x;
}
std::string Get()
{
return m_String;
}
/*std::string* m_String;
public:
Inside(std::string &x)
{
m_String = &x;
}
std::string Get()
{
return
*m_String;
}*/
/*template<typename T>
static T Set(T x)
{
return T;
}*/
};
}
main. cpp
#pragma once
#include<iostream>
#include"Another.h"
#include<memory>
int main()
{
NamespaceAn::Test::Init();
/*auto asdf = NamespaceAn::Test::GetString();
std::cout << asdf << std::endl;*/
std::cout << NamespaceAn::Test::GetString();
std::cin.get();
}
Extra
Внутри Another.cpp
я также пробовал следующий код:
std::string Ast = "asdf";
Outside::Inside* ob = new Outside::Inside(Ast);
auto s_String = &(ob->Get());