在C ++中使用虚函数

Adi*_*yaG 0 c++ virtual function

我在C ++中使用虚函数有一个小问题

我有一个B类,扩展了A类。

Class A{
  virtual function 1 // does nothing 
  virtual function 2 // does nothing
}

class B : public class A {
  function 1 { does some thing }
  function 2 { does some thing }
}
Run Code Online (Sandbox Code Playgroud)

我还有另一个课堂工具

class implement {

  B b;
  A *a = &B;
  a.function 1();
  a.function 2();
}
Run Code Online (Sandbox Code Playgroud)

使用GCC编译器进行编译时,此代码在编译时会产生以下错误

未定义对功能1和功能2的引用

请帮助我提前解决此感谢

Alo*_*ave 5

在C ++中,只允许存在没有函数定义的纯虚函数。
在您的代码中,您没有任何纯虚函数。纯虚函数是=0在声明中具有的虚函数。
例如:

virtual void doSomething()=0;
Run Code Online (Sandbox Code Playgroud)

基类中的virtual成员函数(function1()function2()A 必须具有定义,因为它们不是纯虚拟的。您没有提供它们的定义,因此链接器会适当地抱怨缺少定义。

undefined reference to function 1 and function 2
Run Code Online (Sandbox Code Playgroud)