无法打印指针向量
Unable to print a vector of pointers
我们有一些 classes,class A 的构造函数如下所示:
A::A(int num, bool boods, double diablo, std::vector<ClassB* > &c) {
createobj();
setNum(num);
setboods(boods);
setDiablo(diablo);
c= this->c; //Where c, is just a vector of pointer objects of class B
}
void A::createobj() {
E e("e", 59, 0, 100); //Where E is a derived class inherited from class B
B *e = &e;
c.push_back(e);
}
//Then over at main:
main() {
std::vector<ClassB* > c;
A a(100, true, 1.21, c);
std::cout << c.size(); //prints out 1 as expected...
for(auto i : c){
std::cout << i->getName() << std::endl; //instead of printing "e"
//I get this from the console
//�
//Segmentation Fault
}
}
我已经为此工作了 12 个多小时,非常感谢任何帮助,我会在你的婚礼上跳舞。
c 向量是在 class A 的 .h 中声明的私有指针向量
并且只持有 ClassB* 对象。
这是一个问题:
void A::createobj(){
E e("e", 59, 0, 100);
B *e = &e; // <-- Is this your real code? Anyway, the next line is bad also
c.push_back(e); // <-- The e is a local variable
}
您正在存储指向局部变量 e
的指针,因此当 createobj
returns 时,e
不再存在。
一个解决方案是动态分配您的对象,然后您需要通过发出对 delete
:
的调用在代码中某处释放内存来正确管理它们的生命周期
void A::createobj(){
E* e = new E("e", 59, 0, 100);
c.push_back(e); // <-- ok
}
我们有一些 classes,class A 的构造函数如下所示:
A::A(int num, bool boods, double diablo, std::vector<ClassB* > &c) {
createobj();
setNum(num);
setboods(boods);
setDiablo(diablo);
c= this->c; //Where c, is just a vector of pointer objects of class B
}
void A::createobj() {
E e("e", 59, 0, 100); //Where E is a derived class inherited from class B
B *e = &e;
c.push_back(e);
}
//Then over at main:
main() {
std::vector<ClassB* > c;
A a(100, true, 1.21, c);
std::cout << c.size(); //prints out 1 as expected...
for(auto i : c){
std::cout << i->getName() << std::endl; //instead of printing "e"
//I get this from the console
//�
//Segmentation Fault
}
}
我已经为此工作了 12 个多小时,非常感谢任何帮助,我会在你的婚礼上跳舞。
c 向量是在 class A 的 .h 中声明的私有指针向量 并且只持有 ClassB* 对象。
这是一个问题:
void A::createobj(){
E e("e", 59, 0, 100);
B *e = &e; // <-- Is this your real code? Anyway, the next line is bad also
c.push_back(e); // <-- The e is a local variable
}
您正在存储指向局部变量 e
的指针,因此当 createobj
returns 时,e
不再存在。
一个解决方案是动态分配您的对象,然后您需要通过发出对 delete
:
void A::createobj(){
E* e = new E("e", 59, 0, 100);
c.push_back(e); // <-- ok
}