używanie przeciążonego operatora << w innym przeciążeniu << w innej klasie

Dec 05 2020

Oto problem. Mam klasę B, w której przeładowałem operator << i klasę A, w której operator << również jest przeciążony. Jednak przeciążenie << w klasie B nie wydaje się działać w przeciążeniu << w klasie A. Po prostu zwraca adres b, tak jakby przeciążenie << w klasie B nie istniało.

Każda forma pomocy jest mile widziana

#pragma once
#include <ostream>

using namespace std;

class B {
public:

    B(int x) {
        this->x = x;
    }
    
    friend ostream& operator<<(ostream& os, B& b)
    {
        os << "this is B " << b.x;
        return os; 
    }

private:
    int x;
};
#pragma once
#include <ostream>
#include "B.h"

using namespace std;

class A {
public:

    A(B* b) {
        this->b = b;
        this->x = 0;
    }

    friend ostream& operator<<(ostream& os, A& a)
    {
        os << a.b << endl; //this doesnt work <============
        os << "this is a " << a.x;
        return os;
    }

private:
    int x;
    B* b;
};
#include <iostream>
#include "A.h"
#include "B.h"

using namespace std;

int main()
{
    B* b = new B(1);
    A* a = new A(b);
    cout << *a << "inside a "<< endl;
    cout << *b << "inside b " <<endl;
}

Odpowiedzi

5 SamVarshavchik Dec 05 2020 at 10:37
os << a.b // ...

a.bnie jest B, dla którego zdefiniowałeś przeciążenie, przyjrzyj się bliżej swojemu kodowi:

class A {
private:

    B* b;
};

To jest B *, a nie a B, i nie ma dla tego przeciążenia.

Jeśli chcesz wywołać tutaj przeciążenie, użyj os << (*a.b) // ...;