如何在 C++ 中使类属性类型与在 C# 中一样

How to make a class property type in C ++ as is how it is done in C#

本文关键字:一样 属性 C++ 类型      更新时间:2023-10-16

正如下面的代码在 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;}
}

像这样的东西。

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; }
};

在当前的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;
};

在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;

在类中。