问题描述
我的目标是做一个类的深层副本,但一个虚拟类会导致麻烦。
My objective is to do a deep copy of a class, but a virtual class is causing trouble.
#include<iostream>
using namespace std;
class Vir//pure virtual class
{
public:
virtual void hi()=0;
};
class Handler:public Vir
{
public:
int i;
Handler() {}
Handler(int val):i(val) {}
void hi() {cout<<"Value of i="<<i<<endl;}
int getI() const {return i;}
void setI(int j) {i=j;}
};
class ControlPanel
{
public:
Vir *v;
ControlPanel(const ControlPanel& c)//copy constructor
{
v=new Handler;
v->setI(c.getI());
}
int getI()const {return v->getI();}
void initialize() {v=new Handler(10);}
void hi() {v->hi();}
ControlPanel() {}
~ControlPanel() {delete v;}
};
int main()
{
ControlPanel cc;
cc.initialize();
cc.hi();
ControlPanel bb(cc);//copying cc into bb
}
编译错误消息:
test.cpp: In copy constructor ‘ControlPanel::ControlPanel(const ControlPanel&)’:
test.cpp:28: error: ‘class Vir’ has no member named ‘setI’
test.cpp: In member function ‘int ControlPanel::getI() const’:
test.cpp:30: error: ‘class Vir’ has no member named ‘getI’
更多Handler类(如Handler1,Handler2等),它们继承自Vir,并且有自己独特的成员(如float a;或double b等)。所以,我没有意义,保持所有的吸气剂&在Vir类中所有Handler类的setter函数。我想在Handler类中保留我的getter和setter方法,因为成员对于Handler类是唯一的。
编译器不允许我这样做。帮助?
I plan to have plenty more Handler classes (like Handler1, Handler2 etc) which inherit from Vir and will have their own unique members (like float a; or double b; etc). So it doesn't make sense for me to keep all the getter & setter functions of all Handler classes in the Vir class. I want to keep my getter and setter methods in the Handler classes because the members are unique to the Handler classes.The compiler is not allowing me to do so. Help?
推荐答案
也许我缺少一些东西,但是你不会更好地使用虚拟 像 Maybe I am missing something but would you not be better with a virtual / p> which is implemented in 注意使用协变返回类型 Note the use of the covariant return type i.e. 这使得 这篇关于不能在纯虚拟基类中创建显式函数而完成复制构建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! code>方法
Vir
?这意味着你可以避免在你自己的回答中概述的 ControlPanel
复制构造函数中的讨厌转型。这与@Andrew Aylett在 使用 p>
clone
method on Vir
? This means you can avoid the nasty cast in the ControlPanel
copy constructor outlined in your own answer. This is the same as @Andrew Aylett suggests in his answer with duplicate
being used instead of clone
.Something like
$ b
Handler
to beHandler* Handler::clone() const
{
return new Handler( *this );
}
:: clone
允许返回 Handler *
,而不仅仅是 Vir *
仍然是 Vir :: clone
的有效重写。Handler::clone
is allowed to return a Handler*
rather than just a Vir*
and still be a valid override of Vir::clone
. ControlPanel
复制构造函数ControlPanel( const ControlPanel& c )
: v( c.v->clone() )
{
}