C++11有没有类似于Python的@property修饰符的等价物?

6

我非常喜欢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
不,没有这样的东西。更多文本:https://dev59.com/nGsy5IYBdhLWcg3wtwQd 等等。 - deviantfan
我不确定一个方法怎么可能不是类的成员? - user1159791
2
@user1159791 在C++领域之外的人往往只使用“成员”来表示“数据成员”,而“成员函数”则被称为“方法”。Python中的property可以通过my_int.half访问,而不是my_int.half() - user395760
我明白了...我习惯将类的任何属性或方法都称为“成员”。我不知道人们会把它用作属性的同义词。对我来说这看起来像是一个错误,但只是措辞罢了:p 无论如何,感谢你的提示 - user1159791
@deviantfan 谢谢。我想到可能是这样,但我在谷歌上找不到答案。链接很有启发性。如果你把它作为答案,我会接受的。 - jlconlin
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接