我的问题是:我想要子类QVector,以便添加一些特定于我的上下文的函数。
天真的做法是:
class ClassVector : public QVector<Class> { ... }但是这里的问题是当我需要调用QVector上的几个函数中的一个函数时,它返回新的QVector (或& to本身):
ClassVector cv1, cv2;
auto sum = cv1 + cv2;这是有效的,但和是QVector,因为operator+返回QVector。
有简单的方法让它以某种方式返回ClassVector吗?
对结果调用reinterpret_cast不是我想要做的:/
如果这很重要,我只向ClassVector添加函数,而不添加数据成员。
谢谢你帮忙。
发布于 2014-09-23 13:18:44
如果新的operator+返回一个不同的类型,你当然可以重新实现它.
#include <QVector>
#include <iostream>
class ClassVector : public QVector<int>
{
public:
typedef QVector<int> base_type;
ClassVector operator+ (const ClassVector& other) const
{
ClassVector sum(*this);
static_cast<base_type&>(sum) += other;
return sum;
}
};
int main()
{
ClassVector cv1;
cv1.append(1);
cv1.append(2);
cv1.append(3);
ClassVector cv2;
cv2.append(11);
cv2.append(12);
ClassVector sum = cv1 + cv2;
for (auto&& v : sum)
std::cout << v << std::endl;
}另一个选项是有一个隐式构造函数,用于从QVector<Class>到ClassVector的转换。有点像
class ClassVector : public QVector<int>
{
public:
typedef QVector<int> base_type;
ClassVector() {}
// Allow to convert a QVector<int> into a ClassVector.
ClassVector(const QVector<int>& other) : QVector<int>(other) {}
// ... possibly other constructors + assignment operator
};也适用于你的情况。
但是,如果您不向ClassVector添加新的状态,我也会使用一个空闲函数。
https://stackoverflow.com/questions/25995642
复制相似问题