当我尝试将派生对象传递给一个需要基类引用的函数时,我有一些问题理解为什么gcc会给我一个错误。
class Base
{
public:
virtual void bar(){}
};
class Derived : public Base
{
public:
virtual void bar() {}
};
void foo(Base& base)
{
base.bar();
}
int main()
{
Derived derived();
foo(derived);
return 0;
}
gcc返回以下我无法理解的内容:
In function 'int main()':
29:16: error: invalid initialization of reference of type 'Base&' from expression of type 'Derived()'
foo(derived);
^
19:6: note: in passing argument 1 of 'void foo(Base&)'
void foo(Base& base)
^~~