python - 是否有 C++11 等同于 Python 的 @property 装饰器?

标签 python c++ c++11 decorator

我非常喜欢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++ 中的类似结构吗?我可以用谷歌搜索,但我不确定要搜索的术语。

最佳答案

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

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

关于python - 是否有 C++11 等同于 Python 的 @property 装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23817366/

相关文章:

c++ - 为什么在分配器中允许 `propagate_on_container_swap == false`,因为它可能导致未定义的行为?

php - Python 相当于 PHP 的 date()

python - 创建一个非迭代器可迭代对象

C++ 嵌套类 - 内部/外部关系

c++ - 应用程序崩溃 C++/MFC 的通用日志

c++ - 为什么 std::function 不是有效的模板参数,而函数指针是?

c++ - 如何从另一个命名空间而不是全局命名空间定义函数和数据?

python - 仅当 OpenCV 中存在矩形时才执行操作

python - 我无法导入 urllib2

c++ - 在 dlsym 之后调用 dlclose 是否安全