2014-05-22 39 views
2

我很喜欢Python的@property修饰器;即,是否存在与Python的@property修饰符相当的C++ 11?

class MyInteger: 
    def init(self, i): 
     self.i = i 

    # Using the @property dectorator, half looks like a member not a method 
    @property 
    def half(self): 
     return i/2.0 

在C++中是否有类似的构造可以使用?我可以谷歌它,但我不知道要搜索的术语。

+1

不,不是那样的。更多的文字:http://stackoverflow.com/questions/8368512/does-c11-have-c-style-properties等 – deviantfan

+0

我不知道如何一个方法不是一个类的成员? – user1159791

+2

@ user1159791 C++领域以外的人倾向于只对“数据成员”使用“成员”,“成员函数”是“方法”。一个Python'property'作为'my_int.half'而不是'my_int.half()'来访问。 – delnan

回答

0

不是说你应该,实际上,你不应该这样做。但这里有一个笑声的解决方案(它可能会改进,但嘿它只是为了好玩):

#include <iostream> 

class MyInteger; 

class MyIntegerNoAssign { 
    public: 
     MyIntegerNoAssign() : value_(0) {} 
     MyIntegerNoAssign(int x) : value_(x) {} 

     operator int() { 
      return value_; 
     } 

    private: 
     MyIntegerNoAssign& operator=(int other) { 
      value_ = other; 
      return *this; 
     } 
     int value_; 
     friend class MyInteger; 
}; 

class MyInteger { 
    public: 
     MyInteger() : value_(0) { 
      half = 0; 
     } 
     MyInteger(int x) : value_(x) { 
      half = value_/2; 
     } 

     operator int() { 
      return value_; 
     } 

     MyInteger& operator=(int other) { 
      value_ = other; 
      half.value_ = value_/2; 
      return *this; 
     } 

     MyIntegerNoAssign half; 
    private: 
     int value_; 
}; 

int main() { 
    MyInteger x = 4; 
    std::cout << "Number is:  " << x << "\n"; 
    std::cout << "Half of it is: " << x.half << "\n"; 

    std::cout << "Changing number...\n"; 

    x = 15; 
    std::cout << "Number is:  " << x << "\n"; 
    std::cout << "Half of it is: " << x.half << "\n"; 

    // x.half = 3; Fails compilation.. 
    return 0; 
} 
相关问题