【问题标题】:How to make a class property type in C ++ as is how it is done in C#如何在 C++ 中创建类属性类型,就像在 C# 中一样
【发布时间】:2016-05-22 22:50:40
【问题描述】:

因为下面的代码用于 C# 中的示例目的,我必须在 C++ 中做,如果是这样,你怎么做?

public class MyClassTest{
    public int testint1{get;set;}
    public MyClassTest2 classTest2{get;set;}
}
public class MyClassTest2{
    public int testint2{get;set;}
    public MyClassTest classTest{get;set;}
}

【问题讨论】:

  • C++ 中没有等效的标准,就像 Java 一样。虽然它可能作为 C++17 中的库 shrug.

标签: c++ class


【解决方案1】:

类似的东西。

class MyClassTest {
private:  // optional: C++ classes are private by default
    int testint1;
public:
    int getTestInt1() const { return testint1; }
    void setTestInt1(int t) { testint1 = t; }
};

或者您可以使您的成员名称与众不同并跳过 get/set 关键字:

class MyClassTest {
private:
    int testint1_;
public:
    int testint1() const { return testint1_; }
    void testint1(int t) { testint1_ = t; }
};

【讨论】:

    【解决方案2】:

    在当前的 C++ 标准中没有与此等效的方法,您只需为所需的任何字段创建 getter/setter 方法:

    class MyClass {
    public:
        MyClass() {}
        // note const specifier indicates method guarantees
        // no changes to class instance and noexcept specifier
        // tells compiler that this method is no-throw guaranteed
        int get_x() const noexcept { return x; }
        void set_x(int _x) { x = _x; }
    private: 
        int x;
    };
    

    【讨论】:

      【解决方案3】:

      在 Visual Studio(我的是 2013 年)中,可以这样完成:

      __declspec(property(get = Get, put = Set)) bool Switch;
      
      bool Get() { return m_bSwitch; }
      void Set(bool val) { m_bSwitch = val; }
      
      bool m_bSwitch;
      

      在课堂上。

      【讨论】:

        猜你喜欢
        • 2010-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-06
        • 2021-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多