在尝试在同一类内部进行课程矢量时,我会遇到错误

I get an error when trying to make a vector of classes inside of the same class

本文关键字:程矢量 错误 遇到 内部 一类      更新时间:2023-10-16

我正在尝试与同一班级的校长一起做一堂课,以制作树,但是当我尝试访问向量的插件时,它永远不会工作。我有一个例外:std :: length_error试图访问字符串。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class A {
  public:
  string name;
  vector<A*> children;
};
int main()
{
    A cl;
    cl.name= "HI!";
    for(int i = 0; i < 10;i++) {
        A newCl;
        newCl.name= "World!";
        cl.children.push_back(&newCl);
    }
    for(int i = 0; i < 10;i++) {
        // error here:
        cout << cl.children[i]->name << endl;
    }
    return 0;
}

任何人都知道在C 中制作树的一种更简单的方法,或者如何修复?

问题在此循环中

for(int i = 0; i < 10;i++) {
        A newCl;
        newCl.name= "World!";
        cl.children.push_back(&newCl);
}

变量newCl将在迭代结束时不复存在,并且您将其地址插入向量。当您访问它时,您将访问悬挂的指针,这是不确定的行为,您的程序可能会崩溃,产生垃圾或介于两者之间的任何东西。

您可以按遗忘提出的堆分配,但是在这种情况下,您可能需要考虑将智能指针用于内存管理。

否则,您可以拥有值std::vector<A>而不是指针的矢量,从C 17可能(有关更多详细信息,请参见:我如何声明同一类的成员向量?(

编辑:我澄清了芯片片的评论后std::vector<A>的使用。

您将临时引用作为孩子:

A newCl; 
newCl.name= "World!";
cl.children.push_back(&newCl);

一旦您不在范围之外,孩子们就会悬挂。

A* newCl = new A;

应该修复。但是您必须通过矢量来释放孩子。

如果您有理由使用指针,最好使用智能指针:

vector<shared_ptr<A>> children;

live