subclassing QList and operator+ overloading
- by Milen
I would like to be able to add two QList objects. For example:
QList<int> b;
b.append(10);
b.append(20);
b.append(30);
QList<int> c;
c.append(1);
c.append(2);
c.append(3);
QList<int> d;
d = b + c;
For this reason, I decided to subclass the QList and to overload the operator+.
Here is my code:
class List : public QList<int>
{
public:
List() : QList<int>() {}
// Add QList + QList
friend List operator+(const List& a1, const List& a2);
};
List operator+(const List& a1, const List& a2)
{
List myList;
myList.append(a1[0] + a2[0]);
myList.append(a1[1] + a2[1]);
myList.append(a1[2] + a2[2]);
return myList;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
List b;
b.append(10);
b.append(20);
b.append(30);
List c;
c.append(1);
c.append(2);
c.append(3);
List d;
d = b + c;
List::iterator i;
for(i = d.begin(); i != d.end(); ++i)
qDebug() << *i;
return a.exec();
}
, the result is correct but I am not sure whether this is a good approach. I would like to ask whether there is better solution?