我有以下关系类.我想克隆类Derived,但我得到错误"无法实例化抽象类".我如何克隆派生类?谢谢.
class Base {
public:
virtual ~Base() {}
virtual Base* clone() const = 0;
};
class Derived: public Base {
public:
virtual void func() = 0;
virtual Derived* clone() const {
return new Derived(*this);
}
};
Run Code Online (Sandbox Code Playgroud)
只能实例化具体的类.您必须重新设计Derived的接口才能进行克隆.首先,删除virtual void func()= 0; 然后你就可以编写这段代码了:
class Base {
public:
virtual ~Base() {}
virtual Base* clone() const = 0;
};
class Derived: public Base {
public:
virtual Derived* clone() const {
return new Derived(*this);
}
};
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是将纯虚函数保留在原位并添加一个具体类:
class Base {
public:
virtual ~Base() {}
virtual Base* clone() const = 0;
};
class Derived: public Base {
public:
virtual void func() = 0;
};
class Derived2: public Derived {
public:
virtual void func() {};
virtual Derived2* clone() const {
return new Derived2(*this);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3477 次 |
| 最近记录: |