Deriving a class from an abstract class (C++)

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 02:42:26

问题


I have an abstract class with a pure virtual function f() and i want to create a class inherited from that class, and also override function f(). I seperated the header file and the cpp file. I declared the function f(int) in the header file and the definition is in the cpp file. However, the compiler says the derived class is still abstract. How can i fix it?


回答1:


The functions f() and f(int) do not have the same signature, so the second would not provide an implementation for the first. The signatures of the PVF and the implementation must match exactly.




回答2:


Are you declaring f(int) in your base class as pure virtual or f()?

Pure virtual functions can have definitions inside their base class. A pure virtual function simply says that the derived type must also specify their own implementations of the function f(int).

class Base
{
public:
  virtual void f(int) = 0;
}


Base::f(int)
{
//some code 
}


class Derived : public Base
{
public:
  virtual void f(int)
  {//Implementation is needed in Derived since f(int) is pure virtual
  }
}



回答3:


What about using C++ templates?

template<typename T>
 class Basic{
  public:
   void f(T);
};

template<typename T>
 Basic<T>::f(T t){
   //Do something generic here
 }

You can use template specialization if your function f needs to do something else when it's parameter is a specific type. I'll use string in this example.

template<>
 class Basic<string>{
  public:
   void f(string);
};

template<>
 Basic<string>::f(string t){
   //Do your special thing with a string
}

Hope this helps!



来源:https://stackoverflow.com/questions/2530843/deriving-a-class-from-an-abstract-class-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!