是否有一个与Python的@属性装饰器等价的C++ 11?

2024-10-04 03:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我非常喜欢Python的@property装饰器;例如

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++中是否有类似的构造我可以使用?我可以用谷歌搜索,但我不确定要搜索的术语。在


Tags: theselfinitdefnot装饰propertyclass
1条回答
网友
1楼 · 发布于 2024-10-04 03:22:39

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

#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;
}

相关问题 更多 >