簡體   English   中英

C ++中的賦值運算符模板和復制構造函數

[英]assignment operator template and copy constructor in c++

所以基本上我試圖使用分配運算符來分配2個var:

S solutionCourante, bestSolution; //(S is a template class)
bestSolution = solutionCourante = solutionInitiale;

這是我要處理的運算符:

template <class S, class T>
const Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)
{

this->lSommets = graphe.lSommets->copieListe(graphe.lSommets);
this->lAretes = graphe.lAretes->copieListe(graphe.lAretes);

return *this;
}

這是我的復制構造函數:

template <class S, class T>
Graphe<S,T>::Graphe(const Graphe<S,T> & graphe)
{
 *this = graphe;
}

(我知道構造函數副本的編碼有點錯誤,但是可以工作)

因此,在任何時候,我都能看到“ bestSolution”和“ solutionCourante”不是NULL而是空的,而且我也不明白為什么,因為在我的運算符中填充了“ monGraphe”。 所以好像我在返回值時做錯了,第一次是我試圖做這個運算符。

根據 :

const Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)

graphe是我要復制的項目,我們得到了* this = graphe?

分配運算符應該為“ this”分配一個值,而不是分配一個新值。

template <class S, class T>
Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)
{
    lSommets = graphe.lSommets ? new PElement<Sommet<T>>(*graphe.lSommets) : nullptr;
    lAretes = graphe.lAretes ? new PElement<Arete<S,T>>(*graphe.lAretes) : nullptr;
    prochaineClef = graphe.prochaineClef;
    return *this;
}
template <class S, class T>
Graphe<S,T>::Graphe(const Graphe<S,T> & graphe)
{
    *this = graphe;
}

一般來說,您不應該使用new來返回在堆上分配的內容,因為所有所有權信息都會丟失。 您可能應該嘗試使用諸如std :: unique_ptr之類的智能指針。

答案已經發布,但是使用了讓賦值運算符完成大部分工作的方法。

由於您已經對復制構造函數進行了編碼,因此應使用復制/交換習語來編寫賦值運算符: 什么是復制與交換習語?

通常要做的事情(如果您想讓賦值運算符和復制構造函數協同工作)是讓復制構造函數完成大部分工作,而賦值運算符利用復制構造函數(和析構函數)。

這是使用復制/交換的代碼:

#include <algorithm>
//...
template <class S, class T>
class Graphe 
{
    //...
    friend void swap(Graphe<S,T>& lhs, Graphe<S,T>& rhs)
    {
        std::swap(lhs.lAretes, rhs.lAretes);
        std::swap(lhs.lSommets, rhs.lSommets);
        std::swap(lhs.prochaineClef, rhs.prochaineClef);
    }
  //...
};
//...
template <class S, class T>
Graphe<S,T>::Graphe(const Graphe<S,T> & graphe) : 
{
    lSommets = graphe.lSommets ? new PElement<Sommet<T>>(*graphe.lSommets) : nullptr;
    lAretes = graphe.lAretes ? new PElement<Arete<S,T>>(*graphe.lAretes) : nullptr;
    prochaineClef = graphe.prochaineClef;
}

template <class S, class T>
Graphe<S,T>& Graphe<S,T>::operator = (Graphe<S,T> graphe)
{
    swap(*this, graphe);
    return *this;
}

在模板類中添加了一個名為swap的函數,該函數僅在left和right參數之間交換所有成員。 我強調,你沒有張貼在所有類成員的事件的所有

假設您的副本構造函數沒有錯誤,並且析構函數正在運行並且沒有錯誤,則上面的代碼將正確運行。

編輯:根據TC的注釋建議,將swap功能設置為朋友功能

暫無
暫無

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

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