子类化QVector< T> [英] Subclassing QVector<T>

查看:48
本文介绍了子类化QVector< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题:我想对QVector进行子类化,以便添加一些特定于我的上下文的函数.

Here's my problem: I want to subclass QVector in order to add some function specific to my context.

天真的方法是:

class ClassVector : public QVector<Class> { ... }

但是这里的问题是,当我需要调用QVector上的几个函数之一时,这些函数会返回新的QVector(或对自身返回& amp;)

But problem here is when I need to call one of few functions on QVector which return new QVector (or & to itself):

ClassVector cv1, cv2;
auto sum = cv1 + cv2;

这是有效的,但总和是QVector,因为运算符+返回QVector.

This is valid but sum is QVector, since operator+ return QVector.

是否有一种简单的方法可以使其以某种方式返回ClassVector?

Is there simple way to make it return ClassVector somehow?

在结果上调用reinterpret_cast不是我想要做的:/

Calling reinterpret_cast on the result is not what I want to do :/

如果重要的话,我只向ClassVector添加函数,没有数据成员.

If it's important, I only add functions to ClassVector, no data members.

感谢您的帮助.

推荐答案

如果新的 operator + 将返回不同的类型,则您当然可以重新实现.

If the new operator+ shall return a different type, you can of course re-implement it.

#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 的转换的隐式构造函数.像

Another option would be to have an implicit constructor for the conversion from QVector<Class> to ClassVector. Something like

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
};

在您的情况下也可以使用.

would also work in your case.

但是,如果您不将新状态添加到 ClassVector 中,那么我还将使用一个免费功能.

However, if you do not add new state to ClassVector, I would also go with a free function.

这篇关于子类化QVector&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆