2012-03-16 85 views
1

我有一个名为* graph1的图形指针和内存已分配给它(注:不是问题的一部分,但Graph是模板类)。我还创建了另一个Graph的实例,称为graph2。我呼吁他们重载赋值运算符,像这样析构函数调用后被重载的赋值运算符调用 - C++

Graph<std::string,std::string> *graph1 = new Graph<std::string,std::string>; 
... 
... // Called member functions on graph1 
Graph<std::string,std::string> graph2; 
graph2 = *graph1; 

赋值运算符工作正常,但由于某些原因图形的析构函数也被称为赋值运算符被调用之后。这是正常的还是我没有正确实施赋值运算符?

我这是怎么实现的赋值操作符:

template <typename VertexType, typename EdgeType> 
Graph<VertexType, EdgeType> Graph<VertexType, EdgeType>::operator=(const Graph<VertexType, EdgeType> &source) 
{ 
    std::cout << "\tAssignment Operator called\n\n"; 
    if(this == &source) 
    return *this; 

    this->vecOfVertices = source.vecOfVertices; 
    this->orderPtr = source.orderPtr; 
    this->count = source.count; 
    return *this; 
} 
+0

你知道析构函数在哪个对象上运行吗? – Aatch 2012-03-16 02:01:30

回答

6

赋值运算符的正确定义是

Graph<VertexType, EdgeType>& Graph<VertexType, EdgeType>:: 
    operator=(const Graph<VertexType, EdgeType> &source); 

使用Graph<VertexType, EdgeType>为您的返回类型,要生成一个临时的不必要的创建变量。

+0

哇。我本应该亲眼看到这一点,因为无处不在编写模板参数而感到困惑。谢谢你的帮助! – jbisa 2012-03-16 02:19:17