C++ 指向结构对象作为函数参数的指针-打印时显示奇怪的文本

C++ 指向结构对象作为函数参数的指针-打印时显示奇怪的文本,c++,class,pointers,struct,C++,Class,Pointers,Struct,我有一个类,它包含一个结构。我在类上有一个方法,创建这个结构的新对象,并将其作为指针返回 我在这个类中有另一个方法,它获取指向这个结构的指针并打印出它的数据 唯一的问题是,当我试图打印出来时,控制台中会出现一些奇怪的文本 代码示例(不是实际代码,而是其原理): //头 类TestClass { 公众: 结构测试结构 { int-ID; 字符串名; }; TestClass::TestStruct*CreateStruct(字符串名,int-id); void PrintStruct(TestCl

我有一个类,它包含一个结构。我在类上有一个方法,创建这个结构的新对象,并将其作为指针返回

我在这个类中有另一个方法,它获取指向这个结构的指针并打印出它的数据

唯一的问题是,当我试图打印出来时,控制台中会出现一些奇怪的文本

代码示例(不是实际代码,而是其原理):

//头
类TestClass
{
公众:
结构测试结构
{
int-ID;
字符串名;
};
TestClass::TestStruct*CreateStruct(字符串名,int-id);
void PrintStruct(TestClass:TestStruct*TestStruct);
}
//C++文件
TestClass::TestStruct*TestClass::CreateStruct(字符串名,int-id)
{
TestStruct TestStruct;
testStruct.ID=ID;
testStruct.Name=Name;
TestClass::TestStruct*pStruct=&TestStruct;
返回pStruct;
};
void TestClass::PrintStruct(TestClass::TestStruct*TestStruct)
{

cout ID您正在返回一个指向局部变量的指针,并且遇到了未定义的行为

TestClass::TestStruct* TestClass::CreateStruct(string name, int id)
{
    TestStruct testStruct;
    //...
    TestClass::TestStruct *pStruct = &testStruct;
    return pStruct;
}   //testStruct is destroyed here
    //the pointer pStruct is invalid
要使其工作,您可以返回智能指针或动态分配内存以延长对象的生存期。请记住,您必须明确地删除它:

TestClass::TestStruct* TestClass::CreateStruct(string name, int id)
{

    TestStruct* testStruct = new TestStruct;

    testStruct->ID = id;
    testStruct->Name = name;

    return testStruct;

};
另外,请认真考虑是否确实需要指针。如果可能,请选择自动变量。如果我是你,我会:

TestClass::TestStruct TestClass::CreateStruct(string name, int id)
{

    TestStruct testStruct;
    testStruct.ID = id;
    testStruct.Name = name;
    return testStruct;
};

void TestClass::PrintStruct(const TestClass::TestStruct& testStruct) const
{
    cout << testStruct.ID << "\n";
    cout << testStruct.Name << "\n";
};
TestClass::TestStruct TestClass::CreateStruct(字符串名,int-id)
{
TestStruct TestStruct;
testStruct.ID=ID;
testStruct.Name=Name;
返回testStruct;
};
void TestClass::PrintStruct(常量TestClass::TestStruct&TestStruct)常量
{

还可以听到一声嘟嘟声,然后是一些奇怪的文字。嘟嘟声实际上是由奇怪的符号产生的,但这并不重要,因为未定义的布哈维尔是非常未定义的。第二个例子成功了,我刚刚发现它可能与不再存在的对象有关。我以后如何明确删除它?@Deukalion just
删除
不再需要时返回的指针。
TestClass::TestStruct TestClass::CreateStruct(string name, int id)
{

    TestStruct testStruct;
    testStruct.ID = id;
    testStruct.Name = name;
    return testStruct;
};

void TestClass::PrintStruct(const TestClass::TestStruct& testStruct) const
{
    cout << testStruct.ID << "\n";
    cout << testStruct.Name << "\n";
};