我有 4 个类:1 个Base 、2 个Derived和 1 个Container类。 Container类包含一个Base指针向量。 我想为我的类Container创建一个复制构造函数,它不会将Derived指针转换为Base ,以便之后我可以将Base指针转换为Derived指针。 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
有没有一种方法可以通过指向基数的指针来复制派生类对象? 还是如何创建这样的副本构造函数?
例如:
class Base {
public: Base( int x ) : x( x ) {}
private: int x;
};
class Derived1 : public Base {
public:
Derived( int z, float f ) : Base( z ), f( f ) {}
private:
float f;
};
class Derived2 : public Base {
public:
Derived( int z, string f ) : Base( z ), f( f ) {}
private:
string f;
};
void main()
{
Base * A = new *Base[2];
Base * B = new *Base[2];
A[0] = new Derived1(5,7);
A[1] = new Derived2(5,"Hello");
B[0] = Base(*A[0]);
B[1] = Base(*A[1]);
}
问题是* B [0]是否为Derived1对象,* B [1]是否为Derived2对象? 如果没有,我如何通过指向基类的指针复制派生类? 是否有通过基类或派生类构造复制构造函数的特定方法? 默认的复制构造函数是否足以胜任该示例?
您可以为此提供虚拟方法Clone
:
class Base {
public:
Base(int x) : x(x) {}
virtual ~Base() {}
virtual Base* Clone() const { return new Base(*this); }
private:
int x;
};
class Derived1 : public Base {
public:
Derived1(int z, float f) : Base(z), f(f) {}
virtual Derived1* Clone() const { return new Derived1(*this); }
private:
float f;
};
class Derived2 : public Base {
public:
Derived2(int z, std::string f) : Base(z), f(f) {}
virtual Derived2* Clone() const { return new Derived2(*this); }
private:
std::string f;
};
在main
行的第二行中(除了错别字),构造了Base
类的两个实例,然后您要问,在最后两行中,这些对象是否会以某种方式立即发生变形并成为派生类的实例。 那当然是不可能的。
另外,请检查此答案 。
注意 :我只是在评论您提供的代码和用例。 使用虚拟Clone
功能是复制多态对象的正确设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.