Przesunięcie bitowe - dziwny przypadek

Przesunięcie bitowe - dziwny przypadek
KI
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 29
0

Cześć. Mam taki program:

Kopiuj
 #include <iostream>

using namespace std;
class C
{
public:
    virtual int shift(int n = 2) const { return n << 2; }
};
class D
    : public C
{
public:
    int shift(int n = 1) const { return n << 5; }
};
int main()
{
    const D d;
    const C *c = &d;
    cout << c->shift() << endl;
    return 0;
}

Zwraca wartość 64, więc bierze wartość n = 2 z Klasy C i ciało funkcji z klasy D. Zaczyna działać normalnie po usunięciu const ale nie mam pojęcia czemu. Może ktoś mi to wytłumaczyć?

I w takim przykładzi eprogram zwraca "Klasa B 1" (1 jest w Klasie A)

Kopiuj
 #include <iostream>

using namespace std;

struct A{
    virtual void pokaz(int n = 1) {cout << "klasa A " << n;}
};

struct B: public A{
    void pokaz(int n = 2) {cout << "klasa B " << n;}
};

int main()
{
    B y;
    A* x = &y;
    x->pokaz();
}

Domyślam się, że ma to cos wspólnego z wczesnym i póxnym wiązaniem ale czy mógłby to ktoś dokładniej wyjaśnić ?

n0name_l
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 2412
2

A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined
by the static type of the pointer or reference denoting the object. An overriding function in a derived class
does not acquire default arguments from the function it overrides.

N3797 8.3.6.10.

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.