[英]C++ Copy construct base class pointer
到處搜索,找不到關於我的問題的任何建議。 我正在嘗試為具有私有變量的類創建一個復制構造函數,該私有變量包括一個指向抽象基類的指針。
#include "BaseClass.hh"
ClassA::ClassA()
{ }
/* Copy construct a ClassA object */
ClassA::ClassA(const ClassA& obj)
{
std::map<std::string, BaseClass*>::const_iterator it;
//ClassA copy = obj;
for(it = obj.ind.begin(); it != obj.ind.end(); it++)
{
copy.ind[it->first]=(it->second);
}
}
//in .hh file
private:
std::map<std::string, BaseClass*> ind;
我什至靠近嗎? 如果沒有,我該如何解決?
這里有幾個問題。
++it;
在for循環中重復。 ClassA copy = obj;
從副本構造函數返回后,變量副本將被銷毀。 因此,您不在此處進行任何復制。 value
作為BaseClass指針,因此需要知道要為其分配內存的確切類型。 key
可以在這里提供幫助。 我在這里使用C ++ 11標簽,這只是出於說明目的。 采取想法並根據需要實施它。 如果您觀察到,我沒有在這里釋放內存,請留給您。
class BaseA
{
public:
virtual void Print() = 0;
};
class Derived1A : public BaseA
{
virtual void Print()
{
std::cout << "Derived1A\n";
}
};
class Derived2A : public BaseA
{
virtual void Print()
{
std::cout << "Derived2A\n";
}
};
std::map<std::string, std::function<BaseA*()>> factory;
class ClassA
{
public:
ClassA()
{
for (auto it = factory.begin(); it != factory.end(); ++it)
{
typedef std::pair<const std::string, BaseA*> Pair;
mapType_m.insert(Pair(it->first, it->second()));
}
}
ClassA(const ClassA& other)
{
for (auto it = other.mapType_m.begin(); it != other.mapType_m.end(); ++it)
{
typedef std::pair<const std::string, BaseA*> Pair;
mapType_m.insert(Pair(it->first, factory[it->first]()));
}
}
void Print()
{
for (auto it = mapType_m.begin(); it != mapType_m.end(); ++it)
{
std::cout << "key:" << it->first << "\tValue:";
it->second->Print() ;
std::cout << "\n";
}
}
private:
std::map<std::string, BaseA*> mapType_m;
};
int main()
{
factory["Derived1A"] = []() { return new Derived1A(); };
factory["Derived2A"] = []() { return new Derived2A(); };
ClassA c1;
ClassA c2 = c1;
c2.Print();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.