我有一个基类 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/