C++复制构造基类指针

C++ Copy construct base class pointer

本文关键字:基类 指针 复制 C++      更新时间:2023-10-16

搜索了一下,找不到任何关于我的问题的建议。我正在尝试为具有私有变量的类创建一个复制构造函数,该私有变量包含指向抽象基类的指针。

#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;

我甚至接近吗?如果没有,我该如何解决这个问题?

这里有几个问题。

  1. ++it;在 for 循环中重复。
  2. ClassA copy = obj; 从复制构造函数返回后,变量副本将被销毁。所以,你在这里没有做任何复制。
  3. 如果您希望将映射中的值作为指针放置,则需要为指针变量分配内存。
  4. 由于您将映射中的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();
}