Is there any way i can write a struct's default constructor in C++/CLI

Mage Luzdia 20 Reputation points
2023-01-18T19:10:29.7833333+00:00
// C3417.cpp
// compile with: /clr /c
value class VC {
   VC(){}   // C3417
   // OK
   static VC(){}
   VC(int i){}
};

Here is the sample MS show us about error C3417.But in a spcial case, I have to write the struct's default constructor like VC(){}.

Meanwhile i also find it really occurs in some API/SDK.Because i find the declare by using VS object explorer:

sample

So,how can I write the code so that my C++/CLI assembly can export the default constructor of a struct?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,847 questions
{count} votes

1 answer

Sort by: Most helpful
  1. YujianYao-MSFT 4,291 Reputation points Microsoft Vendor
    2023-01-19T02:57:18.9833333+00:00

    Hi @Mage Luzdia,

    A CLR type—for example, a class or struct—can have a static constructor that can be used to initialize static data members. A static constructor is called at most once, and is called before any static member of the type is accessed the first time.

    using namespace System;
    
    ref class MyClass {
    private:
        static int i = 0;
    
        static MyClass() {
            Console::WriteLine("in static constructor");
            i = 9;
        }
    
    public:
        static void Test() {
            i++;
            Console::WriteLine(i);
        }
    };
    
    int main() {
        MyClass::Test();
        MyClass::Test();
    }
    

    Best regards,

    Elya


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.