c++ - 访问我只想存在于派生类中的函数

标签 c++ oop inheritance

我有一个基类 Base 和几个派生类:Derived1、Derived2 和 Derived3。

我希望在所有这些函数中都有 Function funcOne,这样我就可以像这样定期访问它:

Base* d1 = new Derived1();
Base* d2 = new Derived2();
Base* d3 = new Derived3();

d1->funcOne();
d2->funcOne();
d3->funcOne();

但我只想在 Derived1 类中使用 Function funcTwo。 问题是,我想这样访问它:

d1->funcTwo();

除了在基类中通过某种实现创建一个虚拟 funcTwo 之外,是否可以通过某种方式来实现,例如

void funcTwo(){ cout << "There is no funcTwo for this class" << endl; }

而其他实现仅针对 Derived1 类?

谢谢!

最佳答案

我可以想到两个主要选项。

您可以按照问题中的概述在基类中实现一个虚拟 funcTwo。这通常是不好的做法,因为可能 funcTwo 在 Base、Derived2 和 Derived3 的上下文中没有意义。如果滥用 API 不编译而不是抛出错误,或者更糟的是,静静地失败,那会更好。 这看起来像:

class Base() {virtual void funcTwo() {throw runtime_error("This should not be called");};
Base *d1 = new Derived1;
Base *d2 = new Derived2;
d1->funcTwo(); //fine
d2->funcTwo(); //compiles even though it doesn't make semantic sense, throws an exception

或者,您可以只在 Derived1 中实现 funcTwo。然后,您将在可能的情况下尝试将指针直接指向 Derived1,并在不可能的情况下使用 dynamic_cast。这是更可取的,因为直接调用 Base::funcTwo 将无法编译,并且您的语义更接近您实际尝试表达的内容。

Base *b = new Derived1;
Derived1 *d1 = new Derived1;
Base *d2 = new Derived2;
d1->funcTwo(); //fine
if ((d1 = dynamic_cast<Derived1*>(b)) d1->funcTwo(); //fine
if ((d1 = dynamic_cast<Derived1*>(d2)) d1->funcTwo(); //funcTwo is not called, no errors
b->funcTwo(); //fails to compile

关于c++ - 访问我只想存在于派生类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25722534/

相关文章:

c# - 继承泛型作为函数参数

java - 继承和类型差异

c++ - 在 Visual C++ 编译器中使用 std::initializer_list 2012 年 11 月 CTP

c++ - 自动使用派生类

javascript - 减少对 JavaScript 对象方法的调用次数

javascript - 'var' vs 'this' vs 构造函数参数变量

c++ - 能够拥有一个包含 const 和非 const 指针的数组

c++ - 如何确保不同的 C++ 代码库使用相同的宏?

java - 缺少重要参数/依赖项时抛出什么异常?

java - 实例化(子)类时,您将对象声明为 "type"有什么区别吗?