C++ 复制具有对派生对象的引用的类

C++ 复制具有对派生对象的引用的类,c++,polymorphism,C++,Polymorphism,假设我有三个类,一个抽象类,一个派生类和一个包含派生类的类 class Parent { public: Parent(); void FunctionOne() { cout << "error"; } void FunctionTwo() = 0; } class Child : public Parent { public: Child(); void FunctionOne() { cout << "implement function on

假设我有三个类,一个抽象类,一个派生类和一个包含派生类的类

class Parent {
public:
  Parent();
  void FunctionOne() { cout << "error"; }
  void FunctionTwo() = 0;
}

class Child : public Parent {
public:
  Child();
  void FunctionOne() { cout << "implement function one" ;}
  void FunctionTwo() { cout << "implement function two" ;}
}


class Execute{
public:
  Execute(Parent& newparent) : parent(newparent) ;
  Execute& operator=(const Execute& in) {
          parent = in.parent;
  Run() { parent.functionOne(); parent.functionTwo(); }

private:
  Parent& parent;
}
输出:“执行功能一”“执行功能二”

问题是,当我将它添加到向量时,Execute被复制,这是复制父对象,但不是将子对象复制到父对象并使用多态性,父对象复制的是一个抽象类,我的输出是“error”,我的程序崩溃

vector<Execute> list;
list.push_back( Execute( Child ) );
list[0].run();  // ERROR
向量列表;
list.push_back(执行(子));
列表[0]。运行();//错误
是否存在复制引用以复制子类的方法?我需要切换到指针吗?问题是,由于Execute正在被复制,所以我没有一个简单的方法来管理指向Child的指针的删除。我无法在此计算机上使用Boost或shared_ptr


我在我的帖子中添加了继承,很抱歉遗漏了这一点。我想我已经用execute execute(儿童)解决了这个问题;很抱歉,我试图简化问题,使其易于理解,并可能引入了一些微妙的错误。你能帮我解决我原来的问题吗?

首先,你要在类中存储对临时对象的引用。一旦超出当前范围,您对该
Execute
实例所做的任何操作都将在无效引用上运行

Child c;
vector<Execute> list;
list.push_back( Execute( c ) );
list[0].Run();
要解决此问题,请执行以下操作:

class Execute
{
public:
    Execute(Parent* newparent) : parent(newparent) {}
    Execute(const Execute& e) : parent(e.parent) {} // for the rule of 3

    ~Execute() {} // empty destructor - since you didn't create it, you shouldn't delete it

    Execute& operator=(const Execute& in) 
    {
        parent = in.parent;
        return *this;
    }

    Run() 
    {
        parent.functionOne(); 
        parent.functionTwo(); 
    }

private:
  Parent* parent;
};
然后,当您使用它时:

Parent* p = new Child();
// to show the scoping doesn't destroy p
{
    Execute e(p);
    e.Run();
}
delete p;

您可以在任何容器中传递
Execute
实例,它不会使另一个实例的有效
父成员无效。但是当您处理完它们后,您必须自己清理它们。

如果所有错误都已修复,并且函数声明为虚拟函数,并且可以编译代码,则行为符合预期:

implement function oneimplement function two
正如您提到的,父对象是对某个“原始”对象的引用。此对象必须是动态分配的、全局的或自动的,但要比Execute/vector长。也可以将父变量更改为普通成员变量,而不是引用

Child c;
vector<Execute> list;
list.push_back( Execute( c ) );
list[0].Run();
子c;
向量表;
列表。推回(执行(c));
列表[0]。运行();

您的代码没有继承性。您能修复它以反映您的问题吗?
Excecute execute(Child())大多数情况下肯定不会像您认为的那样执行。它不创建对象,而是声明函数。您需要在引用、指针和值语义之间进行选择。目前,您正在使用引用语义并体验对象切片。
=
是什么意思?这是只有你才能回答的问题。我理解你的意思,但我不太清楚该怎么做。我希望父对象是原始对象的引用,在本例中是子对象。我知道我正在将子对象的“切片”复制到父对象中,这不是我想要的。但是有没有办法做到我想要的?我不确定,所以转到这里寻求帮助。您还没有在
=
上说您想做什么,那么我如何确定是否可以做您想做的事情?假设有
执行一个(alice)
执行两个(bob):您希望
1=2
做什么?不是实现细节,而是您希望它在抽象意义上意味着什么。谢谢,但在我的例子中,父级和执行级将只存在于同一范围内。如果可能的话,我希望避免“赤裸裸”的新指针。你有什么建议吗?你需要以某种方式使用指针(参见为什么引用对你的目标不起作用)。如果无法使用
std::shared_ptr
std::unique_ptr
,则需要编写自己的智能指针类或自行处理内存。