我的代码的内联函数不是存储字符串值



我正在学习一个在线教程,它与我的代码非常相似,但并不完全相同。我对它进行了修改,以便更好地理解它,但在从内联函数获取/返回字符串值时遇到了问题。一旦编译器退出Another.cpp的最后一个大括号,字符串值就会变为空。

有没有什么方法可以在不改变文件结构和代码的情况下解决我的问题?特别是,我不想更改Another.h中的任何内容。如果有人能解释一下内联函数背后的原因,我会非常感激的。

另一个.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();
}

额外

Another.cpp内部,我还尝试了以下代码:

std::string  Ast = "asdf";
Outside::Inside* ob = new Outside::Inside(Ast);
auto s_String = &(ob->Get());

Test::Init中,此行:

auto s_String = Outside::Inside("asdf");

声明了一个局部变量s_String,该局部变量对静态成员变量进行阴影处理。因此,当您退出函数时,您会看到静态成员变量的原始值,该值从未被修改。

相反,只需执行:

s_String = Outside::Inside("asdf");

以分配给静态成员变量。由于s_Stringshared_ptr,您要查找的可能是:

s_String = std::make_shared(Outside::Inside("asdf"));

相关内容

  • 没有找到相关文章

最新更新