Creating set / get methods for a C ++ class

Is there any tool that automatically generates a set and gets methods for the class.

I just create classes very often and would like to have a tool that automatically generates the following functions for each member of the class:

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 met such a macro, but I 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; }

Can anyone know how to do this with MS Visual Studio or eny with another tool?

+3
source share
6 answers

Not a tool, but you can use it Encapsulate Methodin Visual Assist X, for example, which does getter / setter methods for some private member of the class.

, , VAX, .

, , , .

+9

?

, , , . , .

( ) , , , .

+4

Visual Studio, Atomineer Pro Documentation - ​​ getter/setter , .

. :

public:

   ...

private:
    int m_Speed;

,

public:
    // Access the Speed
    int GetSpeed(void) const    { return(m_Speed);  };
    void SetSpeed(int speed)    { m_Speed = speed;  };

    ...

private:
    int m_Speed;

(: "m_" "Get..." - , , . (, _speed, mSpeed, m_speed ..) getter/setter (GetSpeed ​​(), get_speed() ..))


#:

protected int m_Speed;

, auto:

protected int Speed { get; set; }

... :

protected int Speed
{
    get { return(m_Speed); }
    set { m_Speed = value; }
}
private int m_Speed;
+3

Kotti - Visual Assist ( ) .

/, , , .

... facepunchable. ( ).

+2

, python script 10 . , :

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 The generating setter remains as an exercise for the reader .;)

0
source

Visual Studio 2017 has an extension called GS Assist . This gives you the ability to quickly create getters and setters in C ++. Here is the link: https://marketplace.visualstudio.com/items?itemName=SeifSarsar.gsassist

0
source

Source: https://habr.com/ru/post/1748676/


All Articles