我有一个抽象基类,想在派生类中实现一个函数。为什么我必须在派生类中再次声明函数?
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/