我的目标是做一个类的深拷贝,但是一个虚拟类却造成了麻烦。
#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’
我计划拥有更多从 Vir 继承的 Handler 类(如 Handler1、Handler2 等),并将拥有自己独特的成员(如 float a; 或 double b; 等)。因此,将所有 Handler 类的所有 getter 和 setter 函数保留在 Vir 类中对我来说是没有意义的。我想在 Handler 类中保留我的 getter 和 setter 方法,因为这些成员对于 Handler 类是唯一的。编译器不允许我这样做。帮助?