简体   繁体   English

如何删除继承自base class的纯虚拟function?

[英]How do I delete a pure virtual function inherited from base class?

Let's say I have a base class called Human .假设我有一个名为Human的 base class。 Baby and Adult are sub-classes of Human . BabyAdultHuman的子类。 Human has a function run as a pure virtual function and I don't want Baby to inherit run but if I don't override run , Baby would become an abstract class. Human有一个 function 作为纯虚拟 function run ,我不希望Baby继承run但如果我不覆盖runBaby将变成一个抽象的 class。

class Human{
 public:
   // Some human attributes.
   virtual void run()=0;
};

class Adult: public Human{
 public:
   void run(){
      // Adult running function
   }
};

class Baby: public Human{
 public:
   void run()=delete; //error

   // If I don't override `run` then Baby is marked as an abstract class

   void crawl(){
     // Baby crawling function.
   }
};

Error if I mark run with =delete如果我用=delete标记run时出错

prog.cpp:19:10: error: deleted function ‘virtual void Baby::run()’
     void run()=delete;
          ^~~
prog.cpp:6:22: error: overriding non-deleted function ‘virtual void Human::run()’
         virtual void run()=0;
                      ^~~

Might be a bad example but what I want is to inherit everything except for run in Baby .可能是一个不好的例子,但我想要的是继承除run in Baby之外的所有内容。 Is it possible?可能吗?


Disclaimer: I'm not implementing it anywhere.免责声明:我不会在任何地方实施它。 Just out of curiosity.只是出于好奇。

This is not possible.这不可能。 Consider the following code:考虑以下代码:

Human *CreateAPerson() {
  return new Baby();
}

int main() {
  Human *human = CreateAPerson();
  human->run();
}

The compiler would have no way to know that human->run() is illegal.编译器无法知道human->run()是非法的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从纯虚拟基类函数访问派生成员? - How can I access to derived members from a pure virtual base class function? 如何在 UML 类图中表示纯虚函数? - How do I denote a pure virtual function in a UML class diagram? 从继承的虚拟基类定义纯虚函数 - Defining pure virtual functions from inherited virtual base classes 从抽象基类成员函数调用纯虚函数? - Calling Pure Virtual Function From Abstract Base Class Member Function? 如果在两个以上的派生类中定义了纯虚函数,该如何从基类调用纯虚函数 - how to call pure virtual function from base class if that function is defined in more than 2 derived class 从基类实例获取指向(纯)虚函数的指针 - Getting a pointer to a (pure) virtual function from a base class instance 从未定义基类的纯虚函数中调用它? - Calling a pure virtual function from base class that doesn't define it? 从基类构造函数调用纯虚函数 - call to pure virtual function from base class constructor 如何调用纯虚函数? - How do I invoke the pure virtual function? 私有继承:如何创建基类的对象(具有纯虚方法)? - Private Inheritance: How do I make object of the Base Class ( which has got pure virtual methods)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM