无法将派生类传递给函数

时间:2017-05-10 12:53:22

标签: c++ gcc

当我尝试将派生对象传递给一个需要基类引用的函数时,我有一些问题理解为什么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)
      ^~~

0 个答案:

没有答案