在另一个类中的另一个<<重载中使用重载的<<运算符

所以问题来了。我有一个 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;
}

回答

os << a.b // ...

a.b不是 a B,您为其定义了重载,请仔细查看您的代码:

class A {
private:

    B* b;
};

那是 a B *,而不是 a B,并且不存在重载。

如果要在此处调用重载,请使用os << (*a.b) // ...;


以上是在另一个类中的另一个&lt;&lt;重载中使用重载的&lt;&lt;运算符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>