繁体   English   中英

结构的指针以及如何访问元素

[英]Struct's pointer and how to access elements

我想为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;
}
IntList *Numbers = new IntList(10);
Numbers[0] = 1;
cout << Numbers[0] << endl;

Numbers的类型为指向IntList的指针。 自远古以来,指针在C系列中就具有类似数组的语义,因此Numbers[0]并不是对IntList::operator[]的调用,而仅仅是指针的第一个元素,即您在堆上分配的IntList

要么在堆栈上创建它:

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

或至少正确解决:

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

这里的问题是您使Numbers成为指向IntList的指针。 IntList *Numbers = new IntList(10); 需要是IntList Numbers = IntList(10); 这样您就拥有一个IntList对象,而不是指向该对象的指针。 这将允许您调用IntList::operator[]而不是指针的operator[] ,后者只为您提供一个Intlist

然后,您需要delete Numbers; 以及Numbers不再是指针。

你想写

IntList Numbers(10);
Numbers[0] = 1;
cout << Numbers[0] << endl;

您的代码段问题

IntList *Numbers;
auto thisIsNotWhatYouThinkItIs = Numbers[0];

是第二条语句返回IntList因为Numbers是指向IntList实例的指针。

暂无
暂无

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

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