简体   繁体   English

如何使用setter作为插槽在Qt中编写可读的c ++ getter和setter

[英]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. 我正在寻找一种可读的方法来使用setter作为SLOT在我的C ++类中编写getter和setter。

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. 但是上一个问题的答案(参见编辑)指出了一些开销(我并不在乎)以及不必要地使用插槽来获取getter(这就是提出这个问题的动机),这可能会更糟对于那些使用这个类的人来说,看到一些没有动力的插件来吸气。

EDIT: substantial change in the question. 编辑:问题的重大变化。 It was: 它是:

Title: Qt getter & setter as public slot, bad idea? 标题:Qt getter&setter作为公共插槽,坏主意?

I'm writing all getter and setter as public slot. 我正把所有的getter和setter都写成公共插槽。 Actually I use only setter as slots but write them one near each other enhance readability. 实际上我只使用setter作为插槽,但是将它们写成彼此靠近,增强了可读性。

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). 我会说这是一个坏主意,因为它毫无意义,因此它会引发“wtf”(这通常是代码错误的标志)。

It's pointless because Qt signals can't return values, and the sole purpose of a getter is to return a value. 这是没有意义的,因为Qt信号不能返回值,而getter的唯一目的是返回一个值。 So it makes no sense to make getters slots. 因此制作getters插槽毫无意义。

I'm talking about getters only, of course. 当然,我只是在谈论吸气剂。 Setters are perfectly fine (and useful) as slots. Setters非常好(和有用)作为插槽。

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. 每个插槽向类元信息添加一些数据+向moc生成的文件添加一些代码。

Also you can mark setters with Q_SLOT macro. 您还可以使用Q_SLOT宏标记setter。 And place both in same place. 并将两者放在同一个地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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