다른 클래스의 다른 << 오버로드에서 오버로드 된 << 연산자 사용

Dec 05 2020

그래서 여기에 문제가 있습니다. << 연산자를 오버로드 한 클래스 B와 << 연산자도 오버로드 한 클래스 A가 있습니다. 그러나 클래스 B의 << 오버로드는 클래스 A의 << 오버로드에서 작동하지 않는 것 같습니다. 클래스 B의 << 오버로드가 존재하지 않는 것처럼 단순히 b의 주소를 반환합니다.

어떤 도움이라도 대단히 감사하겠습니다.

#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;
}

답변

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

a.bB오버로드를 정의한 이 아닙니다. 코드를 자세히 살펴보십시오.

class A {
private:

    B* b;
};

그것은 a가 B *아니라이며 그것에 B대한 과부하는 존재하지 않습니다.

여기에서 과부하를 호출하려면 os << (*a.b) // ...;