gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:17:29 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com