【问题标题】:C++ nested class methodsC++ 嵌套类方法
【发布时间】:2017-07-29 17:33:05
【问题描述】:

我想创建一个类似这样的结构:

template <typename W>
class Graph {
public:
    struct Vertex {
        std::vector<typename Graph<W>::Vertex> next() {
            return GetNext((*this));
        }
    };
    virtual std::vector<typename Graph<W>::Vertex> GetNext(Vertex v) = 0;
};

(不要查看缺少的字段等)

我尝试过类似的方法,但它给出了各种错误,包括语法错误或“无法实例化”,即使我尝试实例化已覆盖 GetNext 的派生类。

问题是:C++ 中是否允许这种结构以及如何正确实现它?

【问题讨论】:

  • Vertex 内部(以及Graph&lt;W&gt; 内部),您可以简单地使用Vertex 而不是typename Graph&lt;W&gt;::Vertex

标签: c++ class oop templates abstract-class


【解决方案1】:

您的代码的唯一问题是您从Vertex 调用GetNext,但Vertex 没有GetNext 成员函数。

如果你想从Vertex调用Graph的方法,那么你需要一个Graph变量来调用它,例如成员变量:

struct Vertex {
    Graph& graph;

    std::vector<typename Graph<W>::Vertex> next() {
        return graph.GetNext(*this);
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多