是否有一种方法可以防止调用派生类中的特定继承函数
Is there a way to prevent calls to a specific inherited function in a derived class?
考虑以下内容:
class base {
// base class
public:
void doBaseStuff() {
/* do something basic */
}
private:
int someDataMember;
};
class derived : public base {
// this class inherits 'doBaseStuff()' as well as 'someDataMember'
public:
void doDerivedStuff() {
/* do something in addition that only this type of derived class can do */
}
};
class specialDerived : public base {
// say 'doBaseStuff()' doesn't make sense in the context of this class!
// we do not want to inherit that function here
// is there a way to prevent instances of this class from calling it?
// we still want 'someDataMember', so we must derive from the base class
public:
void doSpecialStuff() {
/* do something in addition that only this special derived class can do */
}
};
有一个类作为多个其他类的公共基类。但是,假设基类的一个成员函数不希望出现在派生类中。是否有一种方法来明确禁止继承函数在派生类?
实际上,我们可以讨论一个有1000个成员的基类,并且我们想要继承其中的999个,所以简单地放弃继承并只是复制所有代码将导致非常糟糕的代码可维护性。
使该函数在基类中成为虚函数,并在specialDerived
类中提供它的虚拟实现将有效。但是如果这个函数有一个实际的返回类型,而不是void
呢?然后,specialDerived
类必须提供一个返回某些东西的实现。然后调用者可以假设他们得到的值是有意义的,当它实际上不是,这是一个问题。
在specialDerived
中简单地实现虚函数并在函数体中使用单个throw
可能是一种解决方案,只要存在一些文档明确地声明在此特定派生类型的对象上调用此函数没有意义,并且此操作将抛出。我认为这是一个可能的解决方案,但我不确定这是否是最好的方法。
我假设你只是想确保该方法不是被意外调用,即当它被调用时编译错误是完美的。
您可以简单地在specialDerived
中用删除的定义重写doBaseStuff
:
class specialDerived : public base {
void doBaseStuff() = delete;
public:
void doSpecialStuff() {
/* do something in addition that only this special derived class can do */
}
};
这将阻止任何人使用specialDerived::doBaseStuff
。仍然可以将对specialDerived
的引用转换为对base
的引用,并在结果上调用doBaseStuff
,但如果不将doBaseStuff
设置为virtual
,则无法避免。
- 声明
doBaseStuff
在base
中受保护 - 从
base
派生一个新类base2
,使doBaseStuff
成为public - 从
base2
而不是base
派生999个类 - 从
base
中派生一个类
一样:
class base {
protected:
void doBaseStuff() {
/* do something basic */
}
private:
int someDataMember;
};
class base2 : public base {
public:
using base::doBaseStuff; // make it public
};
class derived : public base2 {
// ...
};
class specialDerived : public base {
// doBaseStuff not public here since we're derived only from base (and not base2) and didn't make it public ourself
};
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- QWidget::p aintEngine:不应再在 QTreeWidget 派生类中调用
- 调用从模板派生的类的静态方法,而不指定模板
- 调用派生类成员函数
- 从基类实例调用派生类方法而不进行强制转换
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 从 c++ 中派生类的析构函数调用虚函数
- 从基类 (C++) 调用派生类中的非虚函数
- 调用不在基类中的派生类函数而不进行动态强制转换,以最大程度地提高性能
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何从 Gtk::窗口调用派生对象的析构函数
- 在dynamic_pointer_cast后调用派生类的构造函数
- 如何使派生类函数在调用时始终调用相同的基类函数?
- C++初始化之前派生类调用基类的方法
- 为什么派生类的实例从基类调用方法?
- 从 Base 引用对象调用派生类的成员
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 基函数中的公共函数,当使用派生对象通过另一个基函数调用时,派生调用基函数