C#-like properties in native C++?

后端 未结 11 1907
南笙
南笙 2020-11-29 04:46

In C# / .NET you can do something like this:

someThing.text = \"blah\";
String blah = someThing.text;

However, the above code does not actu

11条回答
  •  盖世英雄少女心
    2020-11-29 05:15

    I warn you, it is not fully compatible native C++: Microsoft-specific C++ only.

    The Microsoft compiler allows you to use declspec(property), this way:

    struct S {
       int i;
       void putprop(int j) { 
          i = j;
       }
    
       int getprop() {
          return i;
       }
    
       // here you define the property and the functions to call for it
       __declspec(property(get = getprop, put = putprop)) int the_prop;
    };
    
    int main() {
       S s;
       s.the_prop = 5;    // THERE YOU GO
       return s.the_prop;
    }
    

    cf Microsoft Documentation for more details: declspec(property).

提交回复
热议问题