从外部类C ++正确调用嵌套类中的函数

时间:2015-03-11 08:31:29

标签: c++ class templates assignment-operator

对于作业的一部分,我应该为我教授创建的名为HashGraph的类创建一个赋值运算符。

这就是函数原型的样子:

HashGraph<T>& operator = (const HashGraph<T>& rhs);

在这个HashGraph<T>类中,我有一个名为LocalInfo的嵌套私有类,它存储了四个集合(由我的教授定义)和对HashGraph的引用。这是嵌套的私有类:

  private:
    //All methods and operators relating to LocalInfo are defined below, followed by
    //  friend functions for insertion onto output streams of HashGrah and LocalInfo
    class LocalInfo {
      public:
        LocalInfo()                : from_graph(nullptr), out_nodes(hash_str), in_nodes(hash_str), out_edges(hash_pair_str), in_edges(hash_pair_str) {}
        LocalInfo(HashGraph<T>* g) : from_graph(g),       out_nodes(hash_str), in_nodes(hash_str), out_edges(hash_pair_str), in_edges(hash_pair_str) {}
        void connect(HashGraph<T>* g) {from_graph = g;}

        bool operator == (const LocalInfo& rhs) const {
          return this->in_nodes == rhs.in_nodes && this->out_nodes == rhs.out_nodes &&
                 this->in_edges == rhs.in_edges && this->out_edges == rhs.out_edges;
        }
        bool operator != (const LocalInfo& rhs) const {
          return !(*this == rhs);
        }

        //from_graph should point to the HashGraph LocalInfo is in, so LocalInfo
        //  methods (see <<)
        HashGraph<T>* from_graph;
        ics::HashSet<std::string>                        out_nodes;
        ics::HashSet<std::string>                        in_nodes;
        ics::HashSet<ics::pair<std::string,std::string>> out_edges;
        ics::HashSet<ics::pair<std::string,std::string>> in_edges;
   };//LocalInfo

在我的赋值运算符中,我应该将rhs图复制到this并返回新复制的图形。我的教授说我必须使用connect类中的LocalInfo,以便每个复制的LocalInfo对象都会将from_graph重置为新图表(this )。

这是我现在的功能:

template<class T>
HashGraph<T>& HashGraph<T>::operator = (const HashGraph<T>& rhs){
    this->clear();
    for(auto i : rhs.node_values) {
        HashGraph<T>::LocalInfo temp;
        temp.connect(rhs);
        node_values[i.first] = temp; 
    }
    edge_values = rhs.edge_values;
    return *this;
}

然而由于行temp.connect(rhs)而无法编译,其中有no matching function call to HashGraph<int>::LocalInfo::connect(const HashGraph<int>&)

我教授设置的方式是this->clear()清空this HashGraph。要复制node_values地图,我使用他的迭代器迭代rhs.node_values地图。

作为一个注释,他已将其设置为调用node_values[i.first] = temp实际上会在node_values中创建一个键,这是右侧的键,然后将赋值{{1 (该temp对象)进入该键。

但就像我说的那样,这并没有编译。那么如何正确使用LocalInfo

2 个答案:

答案 0 :(得分:2)

该函数需要一个指针,而不是一个对象或引用。

temp.connect(&rhs);

答案 1 :(得分:1)

您确定要连接到rhs而不是this吗? rhs是const HashGraph<int> &,这使您无法修改结构。