简体   繁体   中英

Calling inherited functions and overriding behavior in c++

Why does this give this error - 'void D::func(const D &)': cannot convert argument 1 from 'const C' to 'const D &'

How to correct this, I want to call Base's func from Derived's func but note func is a friend function?

class C
{
public:
    C()
    {
        cout << "in C ctor" << endl;
    }

    friend void func(const C& abc1)
    {
        cout << "in C's func" << endl;
    }
};

class D : public C
{
public:
    D()
    {
        cout << "in D ctor" << endl;
    }

    void func(const D& abc)
    {
        func(static_cast<const C&>(abc));
        cout << "in D's func" << endl;
    }
};

int main()
{
    D d;
    d.func(d);
}

why does this similar eg work though -

https://ideone.com/eNmvng

I'm not sure what that syntaxis does with function visibility, but this works:

class C
{
public:
    C()
    {
        cout << "in C ctor" << endl;
    }

    friend void func(const C& abc1);
};

void func(const C& abc1)
{
    cout << "in C's func" << endl;
}

class D : public C
{
public:
    D()
    {
        cout << "in D ctor" << endl;
    }

    void func(const D& abc)
    {
        ::func(abc);
        cout << "in D's func" << endl;
    }
};

int main()
{
    D d;
    d.func(d);
}

Just for completeness sake, this works too:

class C
{
public:
    C()
    {
        cout << "in C ctor" << endl;
    }

    friend void func(const C& abc1)
    {
        cout << "in C's func" << endl;
    }
};

// Make function visible in global scope
void func(const C& abc1);

class D : public C
{
public:
    D()
    {
        cout << "in D ctor" << endl;
    }

    void func(const D& abc)
    {
        ::func(abc);
        cout << "in D's func" << endl;
    }
};

int main()
{
    D d;
    d.func(d);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM