为 C++ 类生成 set/get 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2981303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate set/get methods for a c++ class
提问by Narek
Is there any tool that generates set and get methods for a class automatically.
是否有任何工具可以自动为类生成 set 和 get 方法。
Just I create classes very frequently and would like to have a tool which for each class-member wil generate the following functions automatically:
只是我非常频繁地创建类,并且希望有一个工具可以为每个类成员自动生成以下函数:
Member_Type getMemberName() const; //in header file
Member_Type getMemberName() const //in source file
{
return member;
}
void setMemberName(const Member_Type & val); //in header
void setMemberName(const Member_Type & val) //in source file
{
member = val;
}
I have met a macro like this but did not like the idea:
我遇到过这样的宏,但不喜欢这个想法:
#define GETSETVAR(type, name) \
private: \
type name; \
public: \
const type& get##name##() const { return name; } \
void set##name##(const type& newval) { name = newval; }
May be someone knows how to do that with MS Visual Studio, or eny other tool?
可能有人知道如何使用 MS Visual Studio 或其他任何工具来做到这一点?
回答by M. Williams
Not the tool actually, but you could use Encapsulate Method
in Visual Assist X, for example, which makes getter / settermethods for some private class member.
实际上不是该工具,但您可以Encapsulate Method
在Visual Assist X 中使用,例如,它为某些私有类成员创建getter/setter方法。
Sure, many of tools that work similiar as VAX do have the same methods.
当然,许多与 VAX 类似的工具确实具有相同的方法。
Also, if you have to do this action for a huge amount of classes, you could implement your own command-line tool and lauch it for every source file that you have.
此外,如果您必须为大量类执行此操作,您可以实现自己的命令行工具并为您拥有的每个源文件启动它。
回答by Mark B
Why do you want to be generating these methods?
为什么要生成这些方法?
Generally a better approach is to make an actual use interface that defines operations on the object, not just sets of individual attributes. By creating a class interface, you avoid the need to write a bunch of getters and setters.
一般来说,更好的方法是制作一个实际使用的接口来定义对对象的操作,而不仅仅是一组单独的属性。通过创建类接口,您无需编写一堆 getter 和 setter。
If you really need to generate public getters and setters for all (or even most) of your attributes, probably better is to just make it a struct, then no such generation is needed.
如果您真的需要为所有(甚至大部分)属性生成公共 getter 和 setter,最好将其设为结构体,那么不需要这样的生成。
回答by Jason Williams
If you're using Visual Studio, my Atomineer Pro Documentationadd-in will do this - it will instantly add getter/setter methods for a member field, using a naming style of your choice.
如果您使用的是 Visual Studio,我的Atomineer Pro 文档插件将执行此操作 - 它将使用您选择的命名样式立即为成员字段添加 getter/setter 方法。
e.g. if you have this:
例如,如果你有这个:
public:
...
private:
int m_Speed;
Then you can execute the command to convert it to this
然后就可以执行命令把它转换成这个了
public:
// Access the Speed
int GetSpeed(void) const { return(m_Speed); };
void SetSpeed(int speed) { m_Speed = speed; };
...
private:
int m_Speed;
(Note: you don't have to use "m_" or "Get..." - this is just an example to show how it handles prefixed or suffixed naming schemes. You can configure the member naming style used (speed, _speed, mSpeed, m_speed, etc) and the naming style for the getter/setter methods (GetSpeed(), get_speed(), etc))
(注意:你不必使用“m_”或“Get...”——这只是一个例子来展示它如何处理前缀或后缀命名方案。你可以配置使用的成员命名风格(速度、_速度、 mSpeed、m_speed 等)和 getter/setter 方法的命名风格(GetSpeed()、get_speed() 等))
It does similar things when applied to a C# member:
当应用于 C# 成员时,它会做类似的事情:
protected int m_Speed;
then you can execute the command to convert it to an auto property:
然后您可以执行命令将其转换为自动属性:
protected int Speed { get; set; }
...and execute the command a second time to produce a property with a backing field:
...并再次执行该命令以生成具有支持字段的属性:
protected int Speed
{
get { return(m_Speed); }
set { m_Speed = value; }
}
private int m_Speed;
回答by peterchen
Agree with Kotti - Visual Assist (and other addins) provide this functionality.
同意 Kotti - Visual Assist(和其他插件)提供此功能。
The actual source code should have the getters / setters, because you probably want to add validation and change notification to the setters as needed.
实际的源代码应该有 getter/setter,因为您可能希望根据需要向 setter 添加验证和更改通知。
Using a macro for that is just... facepunchable. (willing to elaborate on request).
为此使用宏只是......可以打脸。(愿意根据要求详细说明)。
回答by user18853
I could not find a tool so I wrote a python script in 10 minutes. Its not perfect but its helpful:
我找不到工具,所以我在 10 分钟内写了一个 python 脚本。它并不完美,但很有帮助:
generate_getters.py :
generate_getters.py :
#!/usr/bin/python
import sys
if len(sys.argv) < 1:
print 'usage: > python script.py <cpp_file_name>'
fileName = sys.argv[1]
className = fileName.split('.')[-2].split("/")[-1]
print 'classname:' + className
def printGetterSettersForLine(line):
syntax = line.strip().split(';')[0]
words = syntax.split()
if len(words) != 2:
return
getter = words[0] + ' ' + className + '::get' + words[1].title() + '() { \n'
getter = getter + ' return ' + words[1] + ';\n'
getter = getter + '}';
print getter
with open(fileName) as f:
lines = f.readlines()
for line in lines:
printGetterSettersForLine(line)
Usage: > python generate_getters.py ClassName.h Generating setter is left as exercise for reader. ;)
用法: > python generate_getters.py ClassName.h 生成 setter 留给读者练习。;)