Struct Constructor in C++?

前端 未结 16 1784
轻奢々
轻奢々 2020-11-27 08:53

Can a struct have a constructor in C++?

I have been trying to solve this problem but I am not getting the syntax.

16条回答
  •  攒了一身酷
    2020-11-27 09:43

    As the other answers mention, a struct is basically treated as a class in C++. This allows you to have a constructor which can be used to initialise the struct with default values. Below, the constructor takes sz and b as arguments, and initializes the other variables to some default values.

    struct blocknode
    {
        unsigned int bsize;
        bool free;
        unsigned char *bptr;
        blocknode *next;
        blocknode *prev;
    
        blocknode(unsigned int sz, unsigned char *b, bool f = true,
                  blocknode *p = 0, blocknode *n = 0) :
                  bsize(sz), free(f), bptr(b), prev(p), next(n) {}
    };
    

    Usage:

    unsigned char *bptr = new unsigned char[1024];
    blocknode *fblock = new blocknode(1024, btpr);
    

提交回复
热议问题