简体   繁体   中英

Initializing Class members with zero

I have a class in my code that has some integer data members but no methods. Is there exist a way to initialize all the data items with 0 when I create a new object of it using new()?

class A
{
    int x_; 
    int y_; 

    public: 
        A() 
           : 
             x_(0),
             y_(0)
        {} 
};

The part of the A() constructor before the brackets "{}" is called an "initializer list", which you use to initialize the variables to a default value 0 in the case above, or to some other values that may be passed to a constructor that might take those values as arguments. However you initialize an object of type A (eg with "new"), the attributes will be initialized to those values. It is good coding style to initialize the attributes in the same order they are declared, it makes the code more readable.

Value initialization:

struct X
{
    int i, j;
};

X* x = new X(); // The '()' are required.
// 0 == x->i && 0 == x->j
class clasName{
 int x1= 0;
 int x2= 0;
 int x3= 0;
 int x4= 0;
 int x5= 0;
}

Only in C++11.

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