【问题标题】:enum is not a non-static data member or base class of classenum 不是非静态数据成员或类的基类
【发布时间】:2018-04-19 09:52:18
【问题描述】:

嘿,我正在尝试编写 BFS 算法。我的图形类看起来像这样。

class Graph {
    struct Vertice{
        int ID;
        int distance;
        enum color{ WHITE, GREY, BLACK };
        Vertice* parent;
        Vertice(int n) :ID(n), distance(0), color(WHITE), parent(0){};
    };

public:
    Graph(int n) : adjList(n) {

    }

    void add_edge(int u, int v) {
        adjList[u - 1].insert(adjList[u].begin(),Vertice(v));
        adjList[v - 1].insert(adjList[v - 1].begin(), Vertice(u));
    }

    vector<int> shortest_reach(int start) {

    }

    vector<list<Vertice>> adjList;
};

在 struct Vertice 的构造函数的初始化列表中,我收到以下错误 color 不是类 Graph::Vertice 的非静态数据成员或基类。 我尽可能多地用谷歌搜索,但没有找到类似的东西。

【问题讨论】:

  • color是类型名,需要声明该类型的成员字段,

标签: c++ oop breadth-first-search non-static


【解决方案1】:
enum color{ WHITE, GREY, BLACK };

这只会定义值,而不是在每个 Vertice 中实例化其中一个值。

添加另一行也使用一个值:

enum class Color{ WHITE, GREY, BLACK };
Color color;
Vertice* parent;
Vertice(int n) :ID(n), distance(0), color(Color::WHITE), parent(0){};

【讨论】:

    【解决方案2】:

    在上面的代码 sn-p 中,您声明的是类型,而不是 Vertice 的成员。见下面的代码sn-p。

    class Graph {
    
        typedef enum color_t{ WHITE, GREY, BLACK } color_t; // Declare the enum type here.
    
        struct Vertice{
            int ID;
            int distance;
            color_t color; // the member.
    
            Vertice* parent;
            Vertice(int n) :ID(n), distance(0), color(WHITE), parent(0){};
        };
    
    public:
        Graph(int n) : adjList(n) {
    
        }
    
        void add_edge(int u, int v) {
            adjList[u - 1].insert(adjList[u].begin(),Vertice(v));
            adjList[v - 1].insert(adjList[v - 1].begin(), Vertice(u));
        }
    
        vector<int> shortest_reach(int start) {
    
        }
    
        vector<list<Vertice>> adjList;
    };
    

    【讨论】:

      猜你喜欢
      • 2013-11-12
      • 2013-09-14
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 2018-10-05
      • 2013-08-31
      相关资源
      最近更新 更多