简体   繁体   中英

How can I define 2 classes from the same header file, while one class depends on the other?

Im currently trying to implement a simple path-finding algorithm and need edges and nodes for it. I want to handle the implementation of those in one .h and one .cpp file. Right now I get the error "expected constructor, destructor or type conversion before ...".

I already tried separating both classes into 2 .h and .cpp-files, but that didnt work either. I've tried a lot of solutions provided for that error message, but nothing seems to work and I think there something Im missing right now.

My utilites.cpp file looks a bit like that

#include "utilities.h"

//Class Node
//Public

using namespace std;

Node::Node(string name)
{
  this->name = name;
}

//Class Edge
//public

Edge::Edge(Node::Node nSource, Node::Node nTarget, int weight)
{
  this->nSource = nSource;
  this->nTarget = nTarget;
  this->weight = weight;
}

and my utilities.h:

#ifndef UTILITIES_H
#define UTILITIES_H

#include <string>
#include <list>

class Node
{
public:
  Node(std::string);
  std::string name;
};


class Edge
{
public:
  Edge(Node, Node, int);
  Node nSource;
  Node nTarget;
  int weight;
};

#endif /* end of include guard: UTILITIES_H */

If I just use the Class Node, everything works. But if I want implement Class Edge with the Class Node, I'll get the error previously mentioned. I think it is an easy solve, but I just cant figure it out.

I should say that I already tried it with

Edge::Edge(Node nSource, Node nTarget, int weight)
{
  this->nSource = nSource;
  this->nTarget = nTarget;
  this->weight = weight;
}

but that just gave me the error "No matching function for call to 'Node::Node()'

The problem was that I was missing the curly braces after the default constructor of Node

Node(){};

Now it works as intended. Thanks for the answers, they made me look at the default constructor closer again...

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