c++ - 在另一个类中的另一个 << 重载中使用重载的 << 运算符
问题描述
所以这就是问题所在。我有一个 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) // ...
;
推荐阅读
- ios - Swift 5.5 + Apple Core Data — 如何将简单的公式存储为 Core Data 中的项目/属性?
- java - 代码没有第二次抛出异常,尽管程序没有停止
- r - R中的逻辑运算符TRUE / FALSE
- javascript - TypeError:无法读取未定义的属性(读取“地图”)。当我尝试映射一组加密货币时引发错误
- nft - Solana Metaplex Candy Machine `tokenMint` 元数据为空
- python - Dockerfile 命令不在 compose 上运行,但在构建容器后在 CLI 中运行
- python - 错误:无法卸载“PyGObject”。这是一个 distutils 安装的项目
- swiftui - SwiftUI - 更新 Firebase 实时数据库上的数据
- python - 如何使用 python 将包含超链接 .docx 的文档合并到另一个 .docx?
- javascript - 如何将下面的 JS 代码转换为 ES6 类代码