c++ - 基类可以声明一个虚方法但不定义它吗?仍然在派生类中定义

标签 c++ abstract-class virtual c++03

#include <vector>

class M {
    public:
        M(unsigned int);
        unsigned int n;
};

M::M(unsigned int i) { n = i; }

class A {
    protected:
        char t;
    public:
        virtual ~A();
        virtual std::vector<M> foo(unsigned int);
        char getChar();
};

A::~A(){}
std::vector<M> A::foo(unsigned int u) {
    std::vector<M> v;
    return v;
}
char A::getChar() { return t; }

class B : public A {
    public:
        B();
        std::vector<M> foo(unsigned int);
};

B::B() { t = 'b'; }
std::vector<M> B::foo(unsigned int c) {
    std::vector<M> v;
    for (unsigned int i = 0; i < c; i++) {
        v.push_back(i);
    }
    return v;
}

int main() {}

在上面的代码中,我在 A::foo() 中收到警告 unused parameter 'u'。但是,完全删除该函数后,我收到一个错误,指出 B 中存在对 A::foo() 的 undefined reference 。 B 正在实现虚方法,在A 中找不到对定义的引用,但是为什么需要在A 中定义它预期的行为是派生类将始终覆盖基类,换句话说,永远不会调用 A::foo()

为了更具声明性,有没有一种方法可以在基类中声明一个虚拟方法,但只在派生类中定义它?考虑基方法调用永远不会显式发生。

最佳答案

你正在寻找的是所谓的“纯虚函数”,你在类定义中用 = 0 声明它:

class A {
    protected:
        char t;
    public:
        virtual ~A();
        virtual std::vector<M> foo(unsigned int) = 0; // <--
        char getChar();
};

您可以阅读有关纯虚函数及其效果的更多信息 at cppreference.com .

关于c++ - 基类可以声明一个虚方法但不定义它吗?仍然在派生类中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59382493/

相关文章:

c++ - 如何在运行时决定将哪个派生类用作 C++ 中的私有(private)类成员?

c++ - C 和 C++ 之间的主要区别是什么?您什么时候会选择一个而不是另一个?

C++ 错误 : decomposition declaration not permitted in this context

c++ - 关于运算符重载的问题

java - 我们可以使用多态性将抽象类对象作为参数传递吗?

python - 类工厂和抽象基类

c++ - 继承、模板和虚函数(这可能会变得困惑)

c++ - fatal error : arm_acle. h:没有那个文件或目录

java - 抽象类或接口(interface)中的 public static final 字段

C++ 虚函数前向声明