c++ - C++中的虚函数必须实现吗?

标签 c++ virtual

class A
{
public:
    A(){}
    virtual void func();
};
class B:public A
{
    void func(){}
}

如果func没有实现,我定义一个A对象时会出现连接错误。所以为什么?我还没有调用 func

最佳答案

if the func isn't implemented, there will be linkage error when I define one object of A. So why?

因为标准规定在这种情况下必须定义函数(强调我的):

[class.virtual]

A virtual function declared in a class shall be defined, or declared pure ([class.abstract]) in that class, or both; no diagnostic is required ([basic.def.odr]).

由于缺乏对非纯虚函数的定义不符合标准,标准不要求工具链能够成功生成可执行文件。

如果链接器能够诊断出丢失的定义,那么您可以认为自己很幸运,因为标准并未强制要求进行诊断。如果消息含糊不清,好吧,这就是为什么不强制执行诊断的原因。链接器要找出源代码损坏的原因并不容易。

关于c++ - C++中的虚函数必须实现吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359621/

相关文章:

c++ - Boost Multiprecision float128: std::exp 错误: 'no matching function for call'

c++ - C++ 中作为右值的常量(11)

c++ - msvc "the breakpoint will not currently be hit"

c++ - 尽管在派生类中有定义,但基类中的方法不可见;多态性和使用 `virtual` 关键字

c++ - 根据构造函数中的参数创建内部对象?

c++ - 如何检测终端中的unicode字符串宽度?

c++ - 使用 C/C++ 连接 mySQL 数据库?

c++ - C++虚拟定义是否自动继承?

c++ - 如何可靠地调用直接父级的虚函数

linux - 如何在 Linux Ubuntu 中查找虚拟内存地址大小?