Vector 作为用指针定义的 Class 的私有成员:没有错误但行为奇怪

Vector as a Private member of a Class defined with pointer: no error but strange behavior

我不明白为什么以下代码不起作用:没有错误,它只是向我发送以下结果:

世界,您好! 进程返回 -1073741819 (0xC0000005) 执行时间:1.656 秒 按任意键继续。

我将 listInt 定义为私有成员中的向量。它来自我用来定义 Class1 对象的指针吗?

    #include "Class1.h"
    using namespace std;

    Class1::Class1()
    {
        int age(10);
        listInt[0]=age;
        cout <<"address Vector1: "<<&listInt[0] << " -  value1:"<<listInt[0] <<  endl;

    }
    Class1::~Class1()
    {
        //delete listInt;
    }
    void Class1::ClassPrintOut() const
    {

    cout << listInt[0] <<  endl;

    }

Class1.cpp

    #ifndef CLASS1_H_INCLUDED
    #define CLASS1_H_INCLUDED
    #include <vector>
    #include <iostream>

    class Class1
    {
        public:
    Class1();
    ~Class1();
    void ClassPrintOut() const;


        private:
    std::vector<int> listInt;


    };
    #endif

Main.cpp

    #include <iostream>
    #include "Class1.h"
    using namespace std;


    int main()
    {
        cout << "Hello world!" << endl;
        Class1 *test(0);
    test =new Class1();
    test->ClassPrintOut();

    delete test;
    return 0;

    }

您没有明确初始化您的 std::vector<int> listInt 成员。这意味着将使用 std::vector<int> 的默认构造函数。 它初始化一个初始大小为0的向量,因此使用索引0访问它是无效的。

要为您的列表指定初始大小,您应该这样做:

Class1::Class1() : listInt(/* the initial size */) { ... }

这为您提供了一个大小为 /* the initial size */ 且所有元素都初始化为零的向量。

如果要通过动态添加元素来更改大小,请使用 push_backemplace_back:

listInt.push_back(/* element to add */);
listInt.emplace_back(/* element to add */);

两者都将一个元素追加到向量的末尾并将向量的大小增加一。

区别在于 emplace_back 使用您传递给它的参数就地构建新元素,但 push_back 总是复制(或移动)该元素。在你的情况下(std::vector<int>),它们没有区别。