【问题标题】:Can a base class declare a virtual method but not define it? Still defined in derived classes基类可以声明一个虚方法但不定义它吗?仍然在派生类中定义
【发布时间】:2019-12-17 21:38:41
【问题描述】:
#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()B 正在实现虚方法,在A 中找不到对定义的引用,但是如果预期的行为是派生类将始终覆盖基类,为什么需要在A 中定义它,在其他情况下话说,A::foo() 永远不会被调用?

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

【问题讨论】:

  • B 正在实现抽象方法,在 A 中找不到对定义的引用 -- 您发布的代码中没有抽象方法。
  • @PaulMcKenzie 我的错误,我的意思是说“虚拟”。
  • 您接受的答案是如何在 C++ 中创建抽象类。至少一个函数必须是纯虚函数才能使类成为抽象类。

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


【解决方案1】:

你要找的东西叫做“纯虚函数”,你在类定义中用= 0声明它:

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

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

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多