首页 > 解决方案 > 在另一个类中的另一个 << 重载中使用重载的 << 运算符

问题描述

所以这就是问题所在。我有一个 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;
}

标签: c++operator-overloadingoverloadingoperator-keyword

解决方案


os << a.b // ...

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

class A {
private:

    B* b;
};

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

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


推荐阅读