【问题标题】:how to initialize pointer with array using constructor C++如何使用构造函数 C++ 用数组初始化指针
【发布时间】:2020-09-15 13:20:57
【问题描述】:

在struct creat array中创建一个指针,使用for循环初始化-1,10次,使用struct中的方法打印-1,10次。

struct hasha {
    int* arr;
    int l;
    hasha(int no) {
        arr[no];
        l = no;
        for (int i = 0; i < l; i++) {
            arr[i] = -1;
        }
    }
    void print() {
        for (int i = 0; i < l; i++) {
            cout << arr[i] << " ";
        }
    }
};
int main() {
    hasha a(10);
    a.print();
}

【问题讨论】:

  • 谁给了你这个任务也应该为你提供了所需的基础知识,也可以在这里查看:stackoverflow.com/questions/388242/…
  • 使用std::vector,否则您必须手动进行分配/解除分配。
  • std::vector&lt;int&gt; a(10, -1); for (auto e : a) {std::cout &lt;&lt; e &lt;&lt; " ";}.
  • “创造”是什么意思?
  • arr[no] 不创建数组。回顾你最近学到的东西。

标签: c++ pointers methods struct constructor


【解决方案1】:

我认为这是出于学习目的,否则您应该为此使用 std::vector&lt;int&gt;

struct hasha {
    int* arr;
    size_t l;                // size_t is an unsigned int type better suited for sizes

    hasha(size_t no) :       // use the member initializer list (starting with ":")
        arr(new int[no]),    // create the array
        l(no)
    {
        // initialize the array with -1, "l" times using a for loop
        for (size_t i = 0; i < l; ++i) {
            arr[i] = -1;
        }
    }

    // You need to delete the implicitly declared copy ctor and copy assignment operator
    // to forbid copying hasha objects to not free the `int*` multiple times later.
    hasha(const hasha&) = delete;
    hasha& operator=(const hasha&) = delete;

    // You need a destructor to free the memory you allocated:
    ~hasha() {
        delete[] arr;
    }

    void print() {
        for (size_t i = 0; i < l; ++i) {
            std::cout << arr[i] << " ";
        }
    }
};

【讨论】:

  • “更适合大小的无符号整数类型”。虽然我同意,但它是开放的辩论;-)
  • @Jarod42 :-) 是的。始终如一地使用它也有点棘手。
【解决方案2】:

以下构造函数使用数组初始化指针: hasha ::hasha (int a[]) : arr (a) {}

【讨论】:

  • 这有很多问题。它不会初始化数组,而是将指针设置为外部数组。它与问题的目标不符。
  • 这正是作者要求的。
  • 这不会在 -1 创建一个包含 10 个值的数组,并且与显示的 main 函数不兼容。你误解了这个问题。
  • 问题中我唯一能理解的部分是摘要,所以我回复了我能理解的部分。
  • 以后可以在问题的cmets部分要求澄清。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多