Struct的指针以及如何访问元素

van*_*rub 1 c++ c++11 c++14

我想为struct的巫婆构造函数和析构函数创建一个小例子,但我的问题是我不能"打印"Zahlen [0]而我不知道为什么?

感谢任何帮助.

也许我必须用指针参数打印它?

#include <iostream>
using namespace std;

struct IntList{
    int *memory;
    int size;

    // Konstruktur
    IntList(unsigned initialSize = 0) {
        memory = new int[initialSize];// Speicher reservieren (0 erlaubt)
        size = initialSize;
    }

    //Destruktor
    ~IntList() {
        delete []memory; // Speicher freigeben
    }

    // Access Elemnts
    int &operator[](unsigned index) {
        if (index>=size) {throw std::out_of_range("out of bounds");}
        return memory[index];
    }
};



int main()
{
    IntList *Numbers = new IntList(10);
    Numbers[0] = 1;
    cout << Numbers[0] << endl;
    delete Numbers;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

bip*_*pll 5

IntList *Numbers = new IntList(10);
Numbers[0] = 1;
cout << Numbers[0] << endl;
Run Code Online (Sandbox Code Playgroud)

Numbers是指向IntList的指针类型.从远古时代开始,指针在C系列中就有类似数组的语义,所以Numbers[0]不是调用,IntList::operator[]而是仅仅是指针的第一个元素,IntList你已经在堆上分配了.

在堆栈上创建它:

IntList Numbers(10);
Numbers[0] = 1;
cout << Numbers[0] << endl;
// automatically destroyed on exiting scope
Run Code Online (Sandbox Code Playgroud)

或者至少正确地解决它:

IntList *Numbers = new IntList(10);
(*Numbers)[0] = 1;
cout << (*Numbers)[0] << endl;
delete Numbers;
Run Code Online (Sandbox Code Playgroud)