【问题标题】:C++ Copy construct base class pointerC++复制构造函数基类指针
【发布时间】:2012-10-08 02:12:26
【问题描述】:

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

#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' 子句中的 it++ 吗?
  • BaseClass 和 ClassA 有什么关系? ClassA 是否公开继承 BaseClass ?
  • 我认为您首先要解释的是:为什么需要自定义复制构造函数?提供给你的那个做了什么你不希望它做的?还有其他人注意到:ClassA 是否继承自 BaseClass?还是另一种关系?
  • 它不继承BaseClass,它只是作为标题包含进来。编辑代码以包含它。

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


【解决方案1】:

这里有几个问题。

  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 << "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();
}

【讨论】:

  • 1.感谢您的注意,这是来自之前的 while 循环。删除它。
  • 2.好的,了解这部分。 3.和4.我也明白我需要分配内存,但我不知道该怎么做,因为它是一个抽象基类,这意味着 BaseClass* copy = New BaseClass;不工作?我也不知道你的意思是什么关键可以在这里提供帮助:(
  • 哇!感谢您花时间向我详细解释这一点。现在我明白你的意思了。这真的帮助了我。再次感谢!
猜你喜欢
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 2016-04-08
  • 2010-10-21
相关资源
最近更新 更多