MOn*_*DaR 6 c++ polymorphism inheritance pointers
以下代码尝试复制对象并保留原始类型.不幸的是它不起作用(每个复制的对象将成为一个Super而不是与其原始的同一个类).
请注意,copySuper(const Super& givenSuper)不应该知道任何关于子类的信息Super.
有可能做这样的副本吗?或者我是否必须更改定义copySuper?
#include <string>
#include <iostream>
class Super
{
public:
Super() {};
virtual ~Super() {};
virtual std::string toString() const
{
return "I'm Super!";
}
};
class Special : public Super
{
public:
Special() {};
virtual ~Special() {};
virtual std::string toString() const
{
return "I'm Special!";
}
};
Super* copySuper(const Super& givenSuper)
{
Super* superCopy( new Super(givenSuper) );
return superCopy;
}
int main()
{
Special special;
std::cout << special.toString() << std::endl;
std::cout << "---" << std::endl;
Super* specialCopy = copySuper(special);
std::cout << specialCopy->toString() << std::endl;
return 0;
}
//Desired Output:
// # I'm Special!
// # ---
// # I'm Special!
//
//Actual Output:
// # I'm Sepcial!
// # ---
// # I'm Super!
Run Code Online (Sandbox Code Playgroud)
Moo*_*ice 13
试试这个:
class Super
{
public:
Super();// regular ctor
Super(const Super& _rhs); // copy constructor
virtual Super* clone() const {return(new Super(*this));};
}; // eo class Super
class Special : public Super
{
public:
Special() : Super() {};
Special(const Special& _rhs) : Super(_rhs){};
virtual Special* clone() const {return(new Special(*this));};
}; // eo class Special
Run Code Online (Sandbox Code Playgroud)
请注意,我们已经实现了一个clone()函数,Special(以及Super的任何其他衍生物)覆盖以创建正确的副本.
例如:
Super* s = new Super();
Super* s2 = s->clone(); // copy of s
Special* a = new Special();
Special* b = a->clone(); // copy of a
Run Code Online (Sandbox Code Playgroud)
编辑:正如其他评论员指出的那样*this,不是this.这会教我快速打字.
EDIT2:另一个修正.
编辑3:我真的不应该在工作中间这么快地发布.为协变返回类型修改了Special :: clone()的返回类型.