Struct Constructor in C++?

前端 未结 16 1700
轻奢々
轻奢々 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:42

    Yes structures and classes in C++ are the same except that structures members are public by default whereas classes members are private by default. Anything you can do in a class you should be able to do in a structure.

    struct Foo
    {
      Foo()
      {
        // Initialize Foo
      }
    };
    
    0 讨论(0)
  • 2020-11-27 09:42

    In C++, we can declare/define the structure just like class and have the constructors/destructors for the Structures and have variables/functions defined in it. The only difference is the default scope of the variables/functions defined. Other than the above difference, mostly you should be able to imitate the functionality of class using structs.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-27 09:43

    In C++ both struct & class are equal except struct'sdefault member access specifier is public & class has private.

    The reason for having struct in C++ is C++ is a superset of C and must have backward compatible with legacy C types.

    For example if the language user tries to include some C header file legacy-c.h in his C++ code & it contains struct Test {int x,y};. Members of struct Test should be accessible as like C.

    0 讨论(0)
提交回复
热议问题