someThing.text = "blah";
String blah = someThing.text;
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码实际上并没有直接与someThing的文本字符串进行交互,它使用了get和set属性.同样,可以使用只读属性.
有没有办法在本机C++中做类似的事情?(不是C++ .NET)
Moo*_*ice 45
警告:这是一个诙谐的反应,很糟糕!
是的,这有点可能:)
template<typename T>
class Property
{
private:
T& _value;
public:
Property(T& value) : _value(value)
{
} // eo ctor
Property<T>& operator = (const T& val)
{
_value = val;
return *this;
}; // eo operator =
operator const T&() const
{
return _value;
}; // eo operator ()
};
Run Code Online (Sandbox Code Playgroud)
然后声明您的类,为您的成员声明属性:
class Test
{
private:
std::string _label;
int _width;
public:
Test() : Label(_label)
, Width(_width)
{
};
Property<std::string> Label;
Property<int> Width;
};
Run Code Online (Sandbox Code Playgroud)
并调用C#风格!
Test a;
a.Label = "blah";
a.Width = 5;
std::string label = a.Label;
int width = a.Width;
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 20
在.NET中,属性是真实的语法糖get和set在幕后发出的函数(实际上它们不仅仅是语法糖,因为属性在生成的IL中发出并且可以与Reflection一起使用).所以在C++中你需要显式地编写那些函数,因为没有像属性这样的概念.
Ste*_*and 16
我警告你:它不是本机C++; 它只是微软特有的.但你可以使用declspec(property):
struct S {
int i;
void putprop(int j) {
i = j;
}
int getprop() {
return i;
}
__declspec(property(get = getprop, put = putprop)) int the_prop;
};
int main() {
S s;
s.the_prop = 5; // THERE YOU GO
return s.the_prop;
}
Run Code Online (Sandbox Code Playgroud)
Moo-Juice的答案看起来很酷,但有一个缺点:你不能像TC#那样使用像普通表达式这样的属性.
例如,
a.text.c_str()不会编译(‘class Property<std::basic_string<char> >’ has no member named ‘c_str’)std::cout << a.text不会编译(template argument deduction/substitution failed)我建议以下增强功能template<typename T> class Property:
T& operator() ()
{
return _value;
}
T const& operator() () const
{
return _value;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以访问该属性的成员(),例如:
char const *p = a.text().c_str();
Run Code Online (Sandbox Code Playgroud)
并且您可以在必须推导出类型的表达式中使用该属性:
std::cout << a.text();
Run Code Online (Sandbox Code Playgroud)