读完这篇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
之后加上 getters
和 setters
其中 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/