简体   繁体   English

无法打印指针向量

[英]Unable to print a vector of pointers

We have some classes, class A that have a constructor that looks like this:我们有一些类 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
    }
}

I have been working on this for over 12 hours, any help is greatly appreciated and I will dance at your wedding.我已经为此工作了超过 12 个小时,非常感谢任何帮助,我会在你的婚礼上跳舞。

c vector is a private vector of pointers that was declared in class A's.h and only holds ClassB* objects. c 向量是在 class A's.h 中声明的指针的私有向量,并且仅包含 ClassB* 对象。

This is an issue:这是一个问题:

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
}

You are storing pointers to a local variable e , thus when createobj returns, that e no longer exists.您正在存储指向局部变量e的指针,因此当createobj返回时, e不再存在。

One solution is to dynamically allocate your objects, and then you need to manage their lifetimes correctly by deallocating the memory somewhere in your code by issuing calls to delete :一种解决方案是动态分配您的对象,然后您需要通过调用delete来在代码中的某处取消分配 memory 来正确管理它们的生命周期:

void A::createobj(){
    E* e = new E("e", 59, 0, 100);  
    c.push_back(e);  // <-- ok 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM