简体   繁体   中英

Initialize the value in default constructor of an "array" class

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.在此处输入图像描述

// 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.

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]())
{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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