[英]Pure virtual functions with arguments of the same class
我很感激,如果有人能告诉我这里发生了什么:说我宣布以下内容
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;
但事实并非如此(它实际上隐藏了它 - 请参阅为什么虚拟函数被隐藏?对此进行解释),因此Derived
仍然是抽象类,因为您没有在基类中提供纯虚函数的实现。 出于这个原因, Derived
也无法实例化。 无法为基类纯虚函数提供实现的派生类将像基类一样保持抽象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.