C++ 复制构造函数基类指针

标签 c++ c++11 copy-constructor abstract-base-class

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

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

关于C++ 复制构造函数基类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774551/

相关文章:

c++ - C++ 中的结构与数组

c++ - 使用 std::move 实现 "take"方法

c++ - 为什么拥有复制构​​造函数会导致此代码中断?

C++:为我的类型定义了我自己的赋值运算符,现在 .sort() 不会对我的类型的 vector 起作用?

c++ - 虚拟父子关系

c++ - 未定义对 `inflate' 的引用

C++11 类型特征 : Arithmetic user type

c++ - 为通用引用和指向成员的指针推导出冲突类型

c++ - 在将实例作为基础对象传递的函数中使用复制构造函数创建实例的拷贝

c++ - 如何在 else-if 语句中正确使用 or 语句 (||)