C++ 自定义成员到成员 "Pointer" / 访问
C++ Custom Member to Member "Pointer" / Access
几年前我在 google 上搜索时发现了一个巧妙的功能。
它允许使用某种 "function" 来控制对成员变量的访问,但我似乎再也找不到它了。 (我也不确定这是 c++ 特性还是仅特定于 msvc 编译器,因为它在 visual studio 中以红色突出显示,就好像它是标签或其他东西一样)
其背后的理论与此类似:
class A
{
public:
.test(int value)
{
priv = value;
}
private:
int priv = 0;
};
...
A a;
a.test = 14; // Sets priv to 14 ! note no () needed after test´
有人知道那是什么吗?
指定初始化器
如果我不得不推测,您很可能已经看到了 C99 指定的初始化程序
看起来像这样:
MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };
这是 C 唯一的东西,在 C++ 中不存在。已经接受了 C++20 的提案,包括对它们的有限支持:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0329r4.pdf
C++/CLI 属性
想到的另一件事是属性,它是托管 C++ 的一部分。
你会像那样使用它们(来源:https://docs.microsoft.com/en-us/cpp/extensions/property-cpp-component-extensions?view=vs-2019)
public ref class C {
int MyInt;
public:
// property data member
property String ^ Simple_Property;
// property block
property int Property_Block {
int get();
void set(int value) {
MyInt = value;
}
}
};
int C::Property_Block::get() {
return MyInt;
}
int main() {
C ^ MyC = gcnew C();
MyC->Simple_Property = "test";
Console::WriteLine(MyC->Simple_Property);
MyC->Property_Block = 21;
Console::WriteLine(MyC->Property_Block);
}
谢谢大家的回复,但是不,它不像某些人拼命告诉我的那样是 C#。
Microsoft docs - property (C++)
对于那些对它的工作原理感兴趣的人:
struct S
{
int i;
void putprop(int j) {
i = j;
}
int getprop() {
return i;
}
__declspec(property(get = getprop, put = putprop)) int the_prop;
};
S s;
s.the_prop = 5;
int test = s.the_prop;
几年前我在 google 上搜索时发现了一个巧妙的功能。 它允许使用某种 "function" 来控制对成员变量的访问,但我似乎再也找不到它了。 (我也不确定这是 c++ 特性还是仅特定于 msvc 编译器,因为它在 visual studio 中以红色突出显示,就好像它是标签或其他东西一样)
其背后的理论与此类似:
class A
{
public:
.test(int value)
{
priv = value;
}
private:
int priv = 0;
};
...
A a;
a.test = 14; // Sets priv to 14 ! note no () needed after test´
有人知道那是什么吗?
指定初始化器
如果我不得不推测,您很可能已经看到了 C99 指定的初始化程序
看起来像这样:
MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };
这是 C 唯一的东西,在 C++ 中不存在。已经接受了 C++20 的提案,包括对它们的有限支持:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0329r4.pdf
C++/CLI 属性
想到的另一件事是属性,它是托管 C++ 的一部分。
你会像那样使用它们(来源:https://docs.microsoft.com/en-us/cpp/extensions/property-cpp-component-extensions?view=vs-2019)
public ref class C {
int MyInt;
public:
// property data member
property String ^ Simple_Property;
// property block
property int Property_Block {
int get();
void set(int value) {
MyInt = value;
}
}
};
int C::Property_Block::get() {
return MyInt;
}
int main() {
C ^ MyC = gcnew C();
MyC->Simple_Property = "test";
Console::WriteLine(MyC->Simple_Property);
MyC->Property_Block = 21;
Console::WriteLine(MyC->Property_Block);
}
谢谢大家的回复,但是不,它不像某些人拼命告诉我的那样是 C#。
Microsoft docs - property (C++)
对于那些对它的工作原理感兴趣的人:
struct S
{
int i;
void putprop(int j) {
i = j;
}
int getprop() {
return i;
}
__declspec(property(get = getprop, put = putprop)) int the_prop;
};
S s;
s.the_prop = 5;
int test = s.the_prop;