我在 C++ 中使用虚函数时遇到一个小问题
我有一个扩展了 A 类的 B 类。
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 }
}
我有另一个类工具
class implement {
B b;
A *a = &B;
a.function 1();
a.function 2();
}
此代码在使用 GCC 编译器编译时出现以下错误
对函数 1 和函数 2 的 undefined reference 。
请帮我解决这个问题 提前致谢
最佳答案
在 C++ 中,只允许在没有函数定义的情况下存在纯虚函数。
在您的代码中,您没有任何纯虚函数。纯虚函数是那些在声明中有 =0
的函数。
例如:
virtual void doSomething()=0;
基类 A
中的 virtual
成员函数(function1()
和 function2()
) < strong>必须 有一个定义,因为它们不是纯虚拟的。您没有提供它们的定义,因此链接器会适本地提示缺少定义。
undefined reference to function 1 and function 2
关于c++ - 在 C++ 中使用虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15044052/