作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如果有人能告诉我这里发生了什么,我将不胜感激:假设我声明以下内容
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/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!