【发布时间】:2015-12-20 02:02:58
【问题描述】:
如果有人能告诉我这里发生了什么,我将不胜感激:假设我声明以下内容
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;
【问题讨论】:
-
如果你声明
member(Base b)(不带引用),那就意味着每次有人调用member时,参数都会按值传递并复制(如果传递的对象实际上是@ 987654328@,复制过程中会被切片)。 -
是的。一切如预期。使用
Base&。你有什么问题?
标签: c++