【发布时间】:2011-05-06 14:03:52
【问题描述】:
以下代码尝试复制对象并保留原始类型。
不幸的是,它不起作用(每个复制的对象都将成为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!
【问题讨论】:
-
这不应该编译,因为至少指定了一个构造函数,但没有指定一个复制构造函数。
-
这至少与 VS 2008 一起编译
-
你是对的。我一头雾水。哦,好吧,没什么新鲜的。
标签: c++ inheritance pointers polymorphism