Struct Constructor in C++?

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

    Yes, but if you have your structure in a union then you cannot. It is the same as a class.

    struct Example
    {
       unsigned int mTest;
       Example()
       {
       }
    };
    

    Unions will not allow constructors in the structs. You can make a constructor on the union though. This question relates to non-trivial constructors in unions.

    0 讨论(0)
  • 2020-11-27 09:30
    struct HaveSome
    {
       int fun;
       HaveSome()
       {
          fun = 69;
       }
    };
    

    I'd rather initialize inside the constructor so I don't need to keep the order.

    0 讨论(0)
  • 2020-11-27 09:34

    In c++ struct and c++ class have only one difference by default struct members are public and class members are private.

    /*Here, C++ program constructor in struct*/ 
    #include <iostream>
    using namespace std;
    
    struct hello
        {
        public:     //by default also it is public
            hello();    
            ~hello();
        };
    
    hello::hello()
        {
        cout<<"calling constructor...!"<<endl;
        }
    
    hello::~hello()
        {
        cout<<"calling destructor...!"<<endl;
        }
    
    int main()
    {
    hello obj;      //creating a hello obj, calling hello constructor and destructor 
    
    return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 09:35

    In C++ the only difference between a class and a struct is that members and base classes are private by default in classes, whereas they are public by default in structs.

    So structs can have constructors, and the syntax is the same as for classes.

    0 讨论(0)
  • 2020-11-27 09:35

    One more example but using this keyword when setting value in constructor:

    #include <iostream>
    
    using namespace std;
    
    struct Node {
        int value;
    
        Node(int value) {
            this->value = value;
        }
    
        void print()
        {
            cout << this->value << endl;
        }
    };
    
    int main() {
        Node n = Node(10);
        n.print();
    
        return 0;
    }
    

    Compiled with GCC 8.1.0.

    0 讨论(0)
  • 2020-11-27 09:41

    Class, Structure and Union is described in below table in short.

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