C++ 如何在C++;在C语言中也是如此#

C++ 如何在C++;在C语言中也是如此#,c++,class,C++,Class,因为下面的代码是用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#编写的,所以我必须用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;
};
在VisualStudio中(我的是2013年),可以通过以下方式完成:

__declspec(property(get = Get, put = Set)) bool Switch;

bool Get() { return m_bSwitch; }
void Set(bool val) { m_bSwitch = val; }

bool m_bSwitch;

在类中。

与Java一样,C++中没有标准的等价物。尽管它可能是C++17中的一个库,但请耸耸肩。