gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:04:04 25 4
gpt4 key购买 nike

我非常喜欢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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com