在尝试在同一类内部进行课程矢量时,我会遇到错误
I get an error when trying to make a vector of classes inside of the same class
我正在尝试与同一班级的校长一起做一堂课,以制作树,但是当我尝试访问向量的插件时,它永远不会工作。我有一个例外: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
相关文章:
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 磁力计代码:C++ vs C - iosstream,矢量 - 错误iostream:没有这样的文件或目录
- C++-从文本文件读取矢量错误
- 成功完成TLS握手后,服务器关闭时出现错误的SSL例程:SSL3_GET_RECORD:错误的版本号
- C++ 提升示例:创建和管理线程(编译错误)
- C++11 线程段错误
- DirectX 10 IDXGISWAPCHAIN :: GetBuffer多线程CTD错误
- C 11线程汇编错误传递字符串作为复制的引用
- std::线程分段错误
- C++ 矢量错误
- 无法初始化线程矢量
- 在循环中联接线程 - 转换错误
- 从 C++ => C 包装的 API(多线程)传输错误字符串
- 尝试用函数填充线程向量 - 错误
- LNK2005矢量错误
- boost线程锁定错误
- std::矢量<A>错误 C2582:"运算符 ="函数在 中不可用
- 当任何子线程导致错误时,上下文切换到主线程
- Vulkan:“vkFlushMappedMemoryRanges”线程层错误
- C++ - 创建线程编译错误