初始化“数组”的默认构造函数中的值班级

发布于 2025-01-16 03:42:23 字数 495 浏览 3 评论 0原文

当我尝试使用初始值的默认构造函数打印出该数组内的值时,它都是随机垃圾数。

我以为默认构造函数会自动将值分配给 (0,0),但似乎并非如此。我想知道我应该做什么。 在此处输入图像描述

// default constructor that allocates 10 elements
Array::Array()
{
    m_size = 10;
    m_data = new Point[m_size];
} 

这是我的班级私人成员:

class Array {
private:
    int m_size;
    Point* m_data;

另外,如果我尝试将冒号语法设置为 Array::Array():m_size(10),m_data(new Point[10]) 它仍然给我随机数。

When I try to print out the value inside this array with the default constructor of the initial value, it's all random garbage numbers.

I thought the default constructor would automatically assign the value into (0,0), but it seems like it's not. I was wondering what I should do.enter image description here

// default constructor that allocates 10 elements
Array::Array()
{
    m_size = 10;
    m_data = new Point[m_size];
} 

Here is my private member for the class:

class Array {
private:
    int m_size;
    Point* m_data;

Also, if I try to do a colon syntax as
Array::Array():m_size(10),m_data(new Point[10])
it's still giving me random number.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尘曦 2025-01-23 03:42:23

您可以像这样初始化数组:

m_data = new Point[m_size](); // Add the braces on the end for zero itialization.

这也适用于初始化列表:

Array::Array()
    : m_size_(10)
    , m_data(new Point[m_size]())
{}

You can initialize the array like this:

m_data = new Point[m_size](); // Add the braces on the end for zero itialization.

This also works in the initializer list:

Array::Array()
    : m_size_(10)
    , m_data(new Point[m_size]())
{}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文