我有一個名為 Cipher 的純虛擬類
class Cipher
{
public:
//This class doesn't have any data elements
virtual Cipher* clone() const = 0;
virtual ~Cipher() { };
//The class has other functions as well, but they are not relevant to the question
};
Cipher 還有一些其他派生類(例如 CaesarCipher)。問題將是關于 CipherQueue 的,它看起來像這樣:
//I've tried to only include the relevant parts here as well
class CipherQueue: public Cipher
{
std::vector<Cipher*> tarolo;
public:
void add(Cipher* cipher)
{tarolo.push_back(cipher);}
CipherQueue(const CipherQueue& _rhs); //?????
CipherQueue* clone() const; //?????
~CipherQueue()
{
for (size_t i = 0; i < tarolo.size(); i )
{
delete tarolo[i];
}
//tarolo.clear(); //not sure if this is needed
}
CipherQueue 有一個名為tarolo的向量。它包含指向 Cipher 派生類的指標。您可以使用 new 運算子或給定類的 clone 函式(已實作)向此向量添加元素:
CipherQueue example;
example.add(new CaesarCipher(3))
CaesarCipher c(6);
example.add(c.clone());
//It is the job of the CipherQueue class to free up the memory afterwards in both cases
現在的問題是:如何在CipherQueue中實作復制建構式和克隆函式,以便在克隆函式中使用復制建構式,并且克隆函式創建呼叫它的物件的深層副本?我已經制作了我認為是淺拷貝的東西,這不好,因為解構式不適用于淺拷貝。(或者解構式也可能是錯誤的?)我們的目標是讓你可以做這樣的事情:~CipherQueue()
CipherQueue example;
CipherQueue inside; //Let's say that this already has a few elements in it
example.add(inside.clone());
example.add(example.clone()); //This should also work
這是我之前嘗試過的,沒有使用復制建構式(我認為這是一個淺拷貝,因此它會導致我的程式出現分段錯誤):
CipherQueue* clone() const
{
CipherQueue* to_clone = new CipherQueue;
to_clone->tarolo = this->tarolo;
return to_clone;
}
uj5u.com熱心網友回復:
謝謝 Marius Bancila,你是對的,問題是我只是在復制指標,而不是在新向量中創建新物件。我在每個物件上呼叫了 clone(),現在它完美地作業了!這是可用的克隆功能,以防將來有人偶然發現此執行緒:
CipherQueue* clone() const
{
CipherQueue* to_clone = new CipherQueue;
to_clone->tarolo = this->tarolo; //First we copy the pointers
for (size_t i = 0; i < this->tarolo.size(); i )
{
to_clone->tarolo[i] = tarolo[i]->clone(); //Then we use the clone function on each element to actually create new objects, and not just have copied pointers
}
return to_clone;
}
最后,似乎我根本不需要復制建構式。您可以在沒有它的情況下創建克隆功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459982.html
