c++ - 为什么需要重新声明接口(interface)?

标签 c++ inheritance

我有一个抽象基类,想在派生类中实现一个函数。为什么我必须在派生类中再次声明函数?

class base {
public:
    virtual int foo(int) const = 0;
};

class derived : public base {
public:
    int foo(int) const; // Why is this required?
};

int derived::foo(int val) const { return 2*val; }

最佳答案

考虑派生类定义可能在 header 中,而其实现可能在源文件中。 header 通常包含在多个位置(“翻译单元”),每个位置都将独立编译。如果您没有声明覆盖,那么编译器就不会在任何其他翻译单元中知道它。

关于c++ - 为什么需要重新声明接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11222847/

相关文章:

php - 在 PHP 中覆盖扩展类中的命名空间使用

c++ - 如何正确实现与基类不同的版本?

c++ - 是否有可能确定/断言,如果一个虚函数被覆盖,另一个虚函数也被覆盖?

c++ - 如何将 Windows 控件添加到 Visual Studio 2017 中的 C++ 桌面应用程序?

c++ - OpenGL/GLSL - 使用缓冲区对象来获取统一的数组值

c++ - 将值从 char 指针复制到 char 数组

c++ - 将其中一个继承的 protected 成员设为私有(private)

具有更多方法的 Python 子类

C++三元运算符混淆

c++ - 从原始内存和类分析器中推断原始类型