如何从基类指针复制继承的类而不进行拼接
how to copy an inherited class from its base class pointer without splicing?
我有一些麻烦,试图创建一个从指针到它的基类的类的副本。下面的例子最能说明这一点:
#include <iostream>
#include <vector>
class Base {
public:
Base() { }
virtual void test() { std::cout << "I am just the base classn"; }
};
class First : public Base {
public:
First() { }
void test() { std::cout << "This is the First classn"; }
};
class Second : public Base {
public:
Second() { }
void test() { std::cout << "This is the Second classn"; }
};
int main() {
First *f = new First();
Second *s = new Second();
// First, I keep a vector of pointers to their base class
std::vector<Base *> ptrs;
ptrs.push_back(f);
ptrs.push_back(s);
ptrs[0]->test(); // Properly calls the implemented virtual class by inheritor
ptrs[1]->test(); // Properly calls the implemented virtual class by inheritor
// Now, I want to *copy* the class without it being spliced to just the base class
// from the ptrs vector (not from 'f')
First *f2 = new First(*ptrs[0]);
}
我最终得到的错误是:
test.cpp: In function ‘int main()’:
test.cpp:35: error: no matching function for call to ‘First::First(Base&)’
test.cpp:12: note: candidates are: First::First()
test.cpp:10: note: First::First(const First&)
是否有任何方法强制转换这个指针来复制完整的对象,而不仅仅是基类?或者我是否需要存储一个指向继承者的指针才能使其工作?
你可以这样做:
First *f2 = 0;
if ( typeid(*ptrs[0]) == typeid(First))
f2 = new First(*dynamic_cast<First*>(ptrs[0]));
应该可以。
但是更好的方法是在基类中拥有clone()
虚函数,并在派生类中实现它:
class Base
{
public:
virtual ~Base() { } //virtual destructed added by me!
virtual Base *clone() = 0;
};
class First : public Base
{
public:
virtual First *clone() { /* implement it */ } //Covariant return type
};
和
First *f2 = 0;
if ( typeid(*ptrs[0]) == typeid(First))
f2 = ptrs[0]->clone(); //no need to use new
有两点需要注意:
- 我在基类中添加了虚析构函数。请参阅本主题,了解您可能需要它的原因。
- 我在派生类中为
clone()
使用了不同的返回类型。它被称为协变返回类型。
First *fx=(First*)ptrs[0];
First *f2 = new First(*fx);
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何从基类指针复制继承的类而不进行拼接