Struct Constructor in C++?

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

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

    #include 
    
    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.

提交回复
热议问题