【问题标题】:C++ Custom Member to Member "Pointer" / AccessC++ 自定义成员到成员“指针”/访问
【发布时间】:2020-06-24 16:33:23
【问题描述】:

几年前我在 google 上搜索时发现了一个简洁的功能。 它启用了一种“函数”的使用来控制对成员变量的访问,但我似乎再也找不到它了。 (我也不确定这是 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´

有人知道它是什么吗?

【问题讨论】:

  • 这不是合法的 C++ 语法。我认为 C# 的 getset 功能可能具有类似的功能。
  • 我知道它看起来不像 c++ 语法,我知道你在说什么,但它在过去仍然有效,但遗憾的是我再也找不到它了。
  • 您是否在寻找pointers to members
  • 您的意思是friend 关键字吗?
  • 您可以将a.test 设为一个类的实例,operator= 用于赋值,operator int 用于读取值。但这可能不是一个好主意。

标签: c++ class visual-c++ operator-keyword member


【解决方案1】:

感谢大家的回复,但不,这不是一些人拼命想告诉我的 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;

【讨论】:

  • 啊哈,好的。 C++ Builder 也有类似的功能。
【解决方案2】:

指定初始化器

如果我不得不推测,您很可能已经看到了 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-12
    • 2013-05-02
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2015-04-13
    相关资源
    最近更新 更多