Struct Constructor in C++?

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

    All the above answers technically answer the asker's question, but just thought I'd point out a case where you might encounter problems.

    If you declare your struct like this:

    typedef struct{
    int x;
    foo(){};
    } foo;
    

    You will have problems trying to declare a constructor. This is of course because you haven't actually declared a struct named "foo", you've created an anonymous struct and assigned it the alias "foo". This also means you will not be able to use "foo" with a scoping operator in a cpp file:

    foo.h:

    typedef struct{
    int x;
    void myFunc(int y);
    } foo;
    

    foo.cpp:

    //<-- This will not work because the struct "foo" was never declared.
    void foo::myFunc(int y)
    {
      //do something...
    }
    

    To fix this, you must either do this:

    struct foo{
    int x;
    foo(){};
    };
    

    or this:

    typedef struct foo{
    int x;
    foo(){};
    } foo;
    

    Where the latter creates a struct called "foo" and gives it the alias "foo" so you don't have to use the struct keyword when referencing it.

提交回复
热议问题