Does C++11 have C#-style properties?

前端 未结 15 1067
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 03:16

In C#, there is a nice syntax sugar for fields with getter and setter. Moreover, I like the auto-implemented properties which allow me to write

public Foo fo         


        
15条回答
  •  失恋的感觉
    2020-11-28 03:46

    There is nothing in the C++ language that will work across all platforms and compilers.

    But if you're willing to break cross-platform compatibility and commit to a specific compiler you may be able to use such syntax, for example in Microsoft Visual C++ you can do

    // declspec_property.cpp  
    struct S {  
       int i;  
       void putprop(int j) {   
          i = j;  
       }  
    
       int getprop() {  
          return i;  
       }  
    
       __declspec(property(get = getprop, put = putprop)) int the_prop;  
    };  
    
    int main() {  
       S s;  
       s.the_prop = 5;  
       return s.the_prop;  
    }
    

提交回复
热议问题