如何为Visual Studio 2008 C++生成自动属性(get,set)

Mik*_*der 0 c++ oop visual-studio-2008

读过这个关于在Visual Studio中生成getter和setter的问题,并尝试(稍微)所描述的技术,我已经惨遭失败,超越了写Getters and Setters的简单方法.

虽然我认识到封装的概念优势(在这种情况下是一个类的私有成员),但编写25个getter和setter却浪费了空间和时间.

为什么25?除了exageration因子(大约2.5)之外,我只是不知道将来我需要访问那个变量.我想我可以编写一个函数来返回所有这些函数并将其删除,但如果我添加更多成员(通常这样做),则必须在整个代码中更改函数.

我想建议的形式,这里的VS 2008:

string sName { get; set; }
Run Code Online (Sandbox Code Playgroud)

但它不会在C++中编译.这仅适用于.NET和C#吗?

有没有一些整洁的方法来在C++中模拟这个?

Ara*_*raK 5

谢谢@Dan指出这个伎俩 Microsoft Compiler (non-portable)

这是方式:

struct person
{
    std::string m_name;
    void setName(const std::string& p_name)
    {
        m_name = p_name;
    }
    const std::string& getName() const
    {
        return m_name;
    }
    // Here is the name of the property and the get, set(put) functions
    __declspec(property(get = getName, put = setName)) std::string name;
};
int main()
{
    person p;

    p.name = "Hello World!"; // setName(...)
    std::cout << p.name;     // getName(...)
}
Run Code Online (Sandbox Code Playgroud)

创建后member variablesgetterssetters的这些member variables,你创建一个property每个getter/setter对.您可以随意调用它,因为您必须为此属性指定getter和setter.


纯娱乐 :)

#define property(Type, Variable) private: Type Variable; \
      public: const Type##& get##Variable() const { return Variable; }; \
      void set##Variable(const Type& Variable##_) { Variable = Variable##_;}


 struct Test
 {
     property(int, x); property(int, y);
     property(std::string, text);
 };

int main()
{
    Test t;

    t.setx(10);
    t.sety(10);
    t.settext("Hello World at: ");
    std::cout << t.gettext() << " " << t.getx() << ", " << t.gety();
}
Run Code Online (Sandbox Code Playgroud)