简体   繁体   中英

How to write readable c++ getter and setter in Qt with setter as slot

Sorry for the substantial change in the question, see the edits above.

I'm looking for a readable way to write getter and setter in my C++ class using setter as SLOT.

Because my habits I'm used to write getter and setter in the bottom of the class, and with getter near the setter.

Here is how I'm writing now:

#include <QObject>

class MyClass : public QObject
{
    Q_OBJECT

public:
    MyClass(...);
    ~MyClass();

    void myPublicMethod();

public slots:
    void onEvent(...);

protected:
    int myVal;

//---------------------------------------------- getter and setter
public slots:
    void setVal(int v);
    const int getVal();

};

But the answer at the previous question (see the edits) points me out in some overhead (that I didn't care so much about) and unnecessary use of slots for getter (this was what motivated to ask this question) that can be worse for people that uses this class and see some un-motivated slot for getters.

EDIT: substantial change in the question. It was:

Title: Qt getter & setter as public slot, bad idea?

I'm writing all getter and setter as public slot. Actually I use only setter as slots but write them one near each other enhance readability.

Is this a bad idea? Any side effects?

I'd say it's a bad idea because it's pointless, and as such it provokes a "wtf" (which is usually a sign of bad code).

It's pointless because Qt signals can't return values, and the sole purpose of a getter is to return a value. So it makes no sense to make getters slots.

I'm talking about getters only, of course. Setters are perfectly fine (and useful) as slots.

Also, there is some memory overhead with each metamethod a class defines (and maybe some performance overhead when establishing connections, not sure). Not much, but it's something to keep in mind.

You will have no side effect except extra code generation. Each slot adds some data to class meta information + add some code to moc generated files.

Also you can mark setters with Q_SLOT macro. And place both in same place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM