【问题标题】:using overloaded << operator in another << overload in a different class在另一个类中的另一个 << 重载中使用重载的 << 运算符
【发布时间】:2021-03-17 02:13:22
【问题描述】:

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


    【解决方案1】:
    os << a.b // ...
    

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

    class A {
    private:
    
        B* b;
    };
    

    这是B *,而不是B,不存在过载。

    如果要在这里调用重载,请使用os &lt;&lt; (*a.b) // ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多