c++ - 多次实现成员功能

标签 c++

例如,您有这样的情况:

1)具有某些类定义的头文件,其中包含一些成员函数(def.h)。

2)该 header 包含在.cpp文件中,其名称与单独的文件夹中的名称相同。

3).cpp文件与def.h具有相同的功能,但方式不同。

3)然后,将该头文件包含在main.cpp中,并以多种方式调用该函数,并编译整个项目。

问题:它将编译没有错误吗?将选择哪种功能实现?

最佳答案

在两个单独的位置定义函数会违反One Definition Rule

One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined.



要具有明确定义的行为,您应该:
  • 仅链接最终程序
  • 中的定义之一
  • 使用overloads代替
  • 使用多态/继承代替
  • 关于c++ - 多次实现成员功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59966178/

    相关文章:

    c++ - 扩展类时内存泄漏

    c++ - 将二维数组传递给类成员函数

    c++ - 我对吗 &str[0] 指向 len + 1 大小的缓冲区,包括空终止字符

    c++ - 在每个类中包含相同的标题

    c++ - 消除从字符串常量到 ‘char*’ 的弃用转换的最佳方法“

    c++ - 从类中返回可 move 的成员变量

    c++ - 在此 "number of elements"宏中添加虚拟字符的目的是什么?

    c++ - 输出缓冲区不会刷新的情况?

    c++ - boost::interprocess::managed_shared_memory 崩溃程序

    c++ - C:声明后初始化结构变量