簡體   English   中英

如何從同一個頭文件中定義2個類,而另一個類依賴於另一個類?

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

我目前正在嘗試實現一個簡單的路徑尋找算法,並需要邊緣和節點。 我想在一個.h和一個.cpp文件中處理它們的實現。 現在我得到錯誤“期望構造函數,析構函數或類型轉換之前......”。

我已經嘗試將兩個類分成2個.h和.cpp文件,但這也沒有用。 我已經嘗試了很多針對該錯誤消息提供的解決方案,但似乎沒有任何工作,我認為我現在缺少一些東西。

我的utilites.cpp文件看起來有點像

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

和我的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 */

如果我只使用類節點,一切正常。 但是,如果我想使用類節點實現Class Edge,我將得到前面提到的錯誤。 我認為這很容易解決,但我無法弄明白。

我應該說我已經試過了

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

但這只是給了我錯誤“沒有匹配函數調用'Node :: Node()'

問題是我在Node的默認構造函數之后缺少花括號

Node(){};

現在它按預期工作。 感謝您的回答,他們讓我再次看到默認構造函數...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM