减少父子类代码重复
Reducing parent-child class code duplication
我在多态性和父子关系方面遇到了问题。以下面的两个类为例,想象一下我在应用程序中创建了一个"child"对象。在对象之外,我调用的唯一函数是update(),它反过来调用对象中我需要的所有其他函数。此调用序列中唯一在"parent"answers"child"上不同的函数是dosomething2()。
class parent
{
public:
void dosomething1() {}; //amongst other things, calls dosomething2
void dosomething2() {};
void update() {}; //amongst other things, calls dosomething1
}
class child : public parent
{
void dosomething2() {}
}
我意识到,如果我创建一个"child"对象并调用update(),那么只会调用父类函数。我不得不将update()和dosomething1()复制到子类中,然后一切都按预期进行。这不是一个很好的解决方案,因为有很多重复的代码——有办法改进吗?
更新:由于提供了答案,我用虚拟dosomething2()函数更新了父类。现在调用了正确的函数,我不必将dosomething1()复制到子类中。不幸的是,如果我不将update()复制到子类,我会得到一个符号查找错误(父类和子类都在一个库中)。
class parent
{
public:
void dosomething1() {}; //amongst other things, calls dosomething2
virtual void dosomething2() {};
void update() {}; //amongst other things, calls dosomething1
}
class child : public parent
{
void dosomething2() {}
/*void update() {}; //symbol lookup error if this is left uncommented */
}
更新2符号查找错误与代码无关。我做了一个make clean,然后make(它构建了一个.so库和可执行文件),现在一切都按预期进行。
您没有将基类中的函数标记为virtual:
class parent
{
public:
virtual void dosomething1() {}; //amongst other things, calls dosomething2
virtual void dosomething2() {};
void update() {}; //amongst other things, calls dosomething1
}
此外,仅供参考,您正在做的被称为模板方法模式。
如果需要dynamic-polymorphism
,则应在父类中使用关键字virtual
。然后在子类中重新实现或不重新实现虚拟函数。
class parent
{
public:
void dosomething1() {}; //amongst other things, calls dosomething2
virtual void dosomething2() {};
void update() {}; //amongst other things, calls dosomething1
}
您应该将相关函数设置为virtual
。假设您希望从对update()
的调用中调用child
的doSomething1()
和doSomething2()
:
class parent
{
public:
virtual void dosomething1() {}; //amongst other things, calls dosomething2
virtual void dosomething2() {};
void update() {}; //amongst other things, calls dosomething1
}
class child : public parent
{
virtual void dosomething2() {}
}
然后,对child
的update()
的调用将调用派生类的方法(如果可用)。请注意,update() is not virtual, so you should have no filed called
会更新in
子级,否则将隐藏该名称。
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 避免在C++中重复子类定义
- 将QOpenGLWidget子类转换为使用Metal而不是OpenGL的子类是否可行?
- 如何初始化矢量的模板化子类
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 使用子类覆盖基类中定义的函数
- 函数从唯一代码调用正确的子类方法
- 使用哪种模式来执行新代码,只需添加基类的新子类?
- 如何在没有大量代码的情况下将类 A 中的纯虚拟方法绑定到两者的子类中 B 类的方法?
- 为什么此子类代码会导致运行时错误
- C++ 在超类构造函数中运行依赖于子类覆盖的大量变量的代码的正确方法是什么?
- 如何在不复制代码的情况下克隆子类
- 如何在子类中获得相同的方法代码而不重复代码
- 子类中的这种变化是否需要重新编译依赖于超类的代码?
- 在泛型和子类代码中需要相互引用的c++类