简体   繁体   中英

Class object initialization

Hi I know this seems like a really dumb question and honestly I'm lost on what is causing this object error and could really use some help.

I have this class here :

class PriorityQueue {
  public:
    PriorityQueue(std::size_t max_nodes);
    void insert(Key k);
    void insert(KeyValuePair kv);
    KeyValuePair min();
    KeyValuePair removeMin();
    bool isEmpty() const;
    size_t size() const;
    nlohmann::json JSON() const;

  private:
    void heapifyUp(size_t i);
    void heapifyDown(size_t i);
    void removeNode(size_t i);
    Key getKey(size_t i);

    std::vector<KeyValuePair>   nodes_;
    size_t                      max_size_;
    size_t                      size_;

    const static size_t         ROOT = 1;
};  // class PriorityQueue

#endif  // _PRIORITYQUEUE_H_

Everything is properly defined in the corresponding cpp file for it. Now I'm trying to call it in a separate file that includes both as a header.

#include "priorityqueue.cpp"
#include "priorityqueue.h"

But in my main() function when I try to call the class to an object like

PriorityQueue m;

I get the error

no matching function for call to ‘PriorityQueue::PriorityQueue()’
PriorityQueue m;

I know this seems like a really basic C++ question but I have no idea what I am doing wrong. Any help would be greatly appreciated.

At the first, remove #include "priorityqueue.cpp" and just use of #include "priorityqueue.h"

Because your constructor has a parameter :

PriorityQueue(std::size_t max_nodes);

So, you should set max_nodes when you creating an object :

PriorityQueue m(10);

But you can also implement a default constructor with a default parameter :

In the header file

// In this approach you can use a default constructor
// Declaration
class PriorityQueue {
  public:
    PriorityQueue(std::size_t max_nodes = 10);
    ...
};

In the cpp file

// Implementation
PriorityQueue::PriorityQueue(std::size_t max_nodes)
{
    max_size_ = max_nodes;
 // initialize members
}

Then you can create instance like bellow :

PriorityQueue m;      // max_size_ will be set to default value (10)
PriorityQueue n(7);   // max_size_ will be set to 7

Try online

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM