Struct Constructor in C++?

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

    Note that there is one interesting difference (at least with the MS C++ compiler):


    If you have a plain vanilla struct like this

    struct MyStruct {
       int id;
       double x;
       double y;
    } MYSTRUCT;
    

    then somewhere else you might initialize an array of such objects like this:

    MYSTRUCT _pointList[] = { 
       { 1, 1.0, 1.0 }, 
       { 2, 1.0, 2.0 }, 
       { 3, 2.0, 1.0 }
    };
    

    however, as soon as you add a user-defined constructor to MyStruct such as the ones discussed above, you'd get an error like this:

        'MyStruct' : Types with user defined constructors are not aggregate
          : error C2552: '_pointList' : non-aggregates cannot 
         be initialized with initializer list.
    

    So that's at least one other difference between a struct and a class. This kind of initialization may not be good OO practice, but it appears all over the place in the legacy WinSDK c++ code that I support. Just so you know...

提交回复
热议问题