c++ - 如何为 Visual Studio 2008 C++ 生成自动属性(获取、设置)

标签 c++ visual-studio-2008 oop

读完这篇question关于在 Visual Studio 中生成 getter 和 setter 并尝试(某种程度上)所描述的技术,我悲惨地失败了,无法超越编写 getter 和 setter 的普通方法。

虽然我认识到封装的概念优势(在本例中为类的私有(private)成员),但编写 25 个 getter 和 setter 是浪费空间和我的时间。

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

我喜欢建议的表格 here对于 VS 2008:

string sName { get; set; }

但它不会在 C++ 中编译。这只是为了 .NET and C#

有没有一些简洁的方法可以在 C++ 中对此进行模拟?

最佳答案

感谢@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(...)
}

在创建您的 member variables 之后加上 getterssetters其中 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();
}

关于c++ - 如何为 Visual Studio 2008 C++ 生成自动属性(获取、设置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1622298/

相关文章:

c++ - 我们如何调试在 C++ 应用程序中使用的 matlab 制作的 DLL?

c++ - 适用于 Vista/Windows 7 的凭证管理器

c++ - Visual Studio 15 - 是否有更好的方法来查看/解释内存窗口中的内存?

c++ - Visual C++ 2008 和 2005 之间的区别

c# - C# 列表的速度

c++ - 我可以在基类中不指定类型名吗?

c# - 这是一个有效的 XML 文件吗?

c# - 3D 中两个矩形之间的交集

java - 我可以覆盖类对象的新实例吗?

C++ 属性声明