C++复制构造基类指针
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 << "Derived1An";
}
};
class Derived2A : public BaseA
{
virtual void Print()
{
std::cout << "Derived2An";
}
};
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();
}
相关文章:
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 使用基类指针调用基类的值构造函数的语法是什么?
- 如何在基类指针向量的元素上应用重载的多态函数
- C++函数解析基类指针到派生类指针
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- 从基类指针派生派生类的模板类型
- 当键是虚拟继承中涉及的基类指针时,对 std::unordered_map 项的访问崩溃
- 如何使用函数(而不是构造函数)将派生类对象分配给基类指针
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- 无法将派生类存储在基类指针的向量中
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 基类指针:在哪里使用 new 和 delete
- 如何在CRTP实现中传递基类指针
- C++继承从基类指针访问派生类中的非虚拟函数
- 通过基类指针获取派生类对象的引用
- C++通过基类指针提升子类的序列化
- 将派生对象分配给函数内的基类指针
- 如果基类指针无法访问派生类成员函数,那么多态性有什么方便的呢?