c++ - 具有同一类参数的纯虚函数

标签 c++

如果有人能告诉我这里发生了什么,我将不胜感激:假设我声明以下内容

class Base {
public:
    virtual void member(Base b) = 0;
};

它给出以下编译器错误:

pvf.cpp:3:18: error: cannot declare parameter ‘b’ to be of abstract type ‘Base’
     virtual void member(Base b) = 0;
              ^
pvf.cpp:1:7: note:   because the following virtual functions are pure within ‘Base’:
     class Base {
   ^
pvf.cpp:3:18: note:     virtual void Base::member(Base)
     virtual void member(Base b) = 0;

但是,如果我通过引用传递,它编译没有问题:

class Base {
public:
    virtual void member(Base& b) = 0;
};

此外,我想在派生类中实现 member() 作为

class Base {
public:
virtual void member(Base& b) = 0;
};

class Derived : public Base {
public:
    void member(Derived& d) {};
};

int main() {
    Derived d;
}

但是,(显然?)我明白了

pvf.cpp: In function ‘int main()’:
pvf.cpp:12:14: error: cannot declare variable ‘d’ to be of abstract type ‘Derived’
    Derived d;
    ^
pvf.cpp:6:8: note:   because the following virtual functions are pure within ‘Derived’:
    class Derived : public Base {
    ^
pvf.cpp:3:15: note:     virtual void Base::member(Base&)
    virtual void member(Base& b) = 0;

最佳答案

你的第一个函数

virtual void member(Base b) = 0;

按值获取类Base 的参数,这需要将Base实例 传递给它。但是由于 Base 是一个抽象类(因为它包含一个纯虚函数),它不能被实例化,因此你不能创建一个 Base 的实例来传递给它!这就是您出现第一个错误的原因。

在第二种情况下,您在派生类中声明了一个函数

void member(Derived& d) {};

你可能认为它覆盖了基类虚函数

virtual void member(Base& b) = 0;

但它没有(事实上,它隐藏了它 - 参见 Why does a virtual function get hidden? 对此的解释),所以 Derived 仍然是抽象类,因为你没有在基类中提供了纯虚函数的实现。由于这个原因,Derived 也无法实例化。无法为基类纯虚函数提供实现的派生类将像基类一样保持抽象。

关于c++ - 具有同一类参数的纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727955/

相关文章:

c++ - Arduino/c++ 在另一个类中使用 SoftwareSerial 类

c++ - OpenMp:如何使维度 std::vector 线程私有(private)

c++ - "there is no smaller array object that satisfies these constraints"是什么意思?

c++ - 递归函数中的返回类型推导

c++ - 如何从旋转角度计算 OpenCV 的透视变换?

c# - C++/CLI 代码中的内存泄漏。我做错了什么?

c++ - 使用 SSE/AVX 内在函数的快速点积

c++ - 数字文字上的 ULL 后缀

c++ - 汉字Uuid转换结果

C++ 编译时检查副作用