如何继承返回对当前对象的引用的方法?

How to inherit methods that return a reference to the current object?

本文关键字:对象 引用 方法 何继承 继承 返回      更新时间:2023-10-16

有一个基类

class LineEditItem
{
public:
LineEditItem(QLineEdit* le, const Values_t& values = Values_t()):
values(values),
le(le)
{}
LineEditItem &addValue(int v, const QString &s)
{
values[v] = s;
return *this;
}
LineEditItem &addValues(const Values_t& vals)
{
for (auto key: vals.keys())
{
values[key] = vals[key];
}
return *this;
}
void setValue(uint32_t v)
{
QString str;
if (values.contains(v))
{
str = values[v];
}
else
{
str = "";
}
le->setText(str);
}
void clearValue()
{
le->clear();
}
protected:
Values_t values;
QLineEdit* le;
};

有一个子类必须继承 addValue 和 addValues 方法

class LineEditItemBits: public LineEditItem
{
public:
LineEditItemBits(QLineEdit* le, int begin, int end, const Values_t& values = Values_t()):
LineEditItem(le, values),
begin(begin),
end(end)
{}
void setValue(uint32_t v)
{
int s = end - begin + 1;
v = (v >> begin) & ((1 << s) - 1);
LineEditItem::setValue(v);
}
LineEditItemBits &addValue(int v, const QString &s)
{
LineEditItem::addValue(v, s);
return *this;
}
LineEditItemBits &addValues(const Values_t& vals)
{
LineEditItem::addValues(vals);
return *this;
}
private:
int begin;
int end;
};

但是您必须显式规定这些方法并从中调用基类方法。 如何从基类继承这些方法,以便它们返回对子类的引用?

据我了解,您正在尝试覆盖这些函数,因此您应该将它们virtual父类中。