Scott
Scott

Reputation: 157

QVector with custom objects that have arguments?

I`m trying to use a QVector with a custom object named RoutineItem.

But this error is given:

C:\Qt\5.2.1\mingw48_32\include\QtCore\qvector.h:265: error: no matching function for call to 'RoutineItem::RoutineItem()'

This is the RoutineItem constructor:

RoutineItem(QString Name,int Position,int Time,bool hasCountdown = false,bool fastNext = false);

If I remove all the constructor arguments I no longer get that error. How can I use QVector with a custom object that has arguments?

Upvotes: 2

Views: 3610

Answers (3)

If you're willing to use C++11 and std::vector, there's no more requirement for default-constructability:

void test()
{
   class C {
   public:
      explicit C(int) {}
   };

   std::vector<C> v;
   v.push_back(C(1));
   v.push_back(C(2));
}

This code won't work pre-C++11, and it won't work with QVector.

Upvotes: 2

P0W
P0W

Reputation: 47784

Provide the non-default arguments in QVector constructor

Example: following creates 10 RoutineItem elements with same Name, Position, Time

QVector<RoutineItem> foo(10, RoutineItem("name", 123, 100 ));
                                            ^     ^     ^
                                            |     |     |
                                            +-----+-----+-----Provide arguments

Upvotes: 2

vahancho
vahancho

Reputation: 21220

The problem is that QVector requires that the element has a default constructor (that is the error message about). You can define one in your class. For example:

class RoutineItem {
    RoutineItem(QString Name, int Position,
                int Time, bool hasCountdown = false,
                bool fastNext = false);
    RoutineItem();
    [..]
};

Alternatively, you can let all arguments have a default values:

class RoutineItem {
    RoutineItem(QString Name = QString(), int Position = 0,
                int Time = 0, bool hasCountdown = false,
                bool fastNext = false);
    [..]
};

Alternatively, you can construct a default value of RoutineItem and initialize all vector items by it:

RoutineItem item("Item", 0, 0);
// Create a vector of 10 elements and initialize them with `item` value
QVector<RoutineItem> vector(10, item);

Upvotes: 7

Related Questions