C++11中有没有相当于Python的@property装饰器的东西?

6 投票
1 回答
1278 浏览
提问于 2025-04-18 07:20

我非常喜欢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++中有没有类似的东西可以用呢?我可以去网上搜索,但我不太确定该用什么词来搜索。

1 个回答

2

我不是说你应该这样做,实际上,你不应该这么做。不过,这里有个搞笑的解决方案(可能还有改进的空间,但这只是为了好玩):

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

撰写回答