c++ - 如何将重载的 ostream 运算符与指向对象的指针数组一起使用?
问题描述
在下面的代码中,我如何使用重载的“<<”运算符来打印所需的信息,而不是使用新函数“void print()”?
或者更准确地说,这里的错误在哪里?
在继承的类之一中重载 << 运算符:
friend ostream &operator<<(ostream &os, DigitSecret &s){
for(int i=0;i<s.n;i++)
os<<s.digits[i];
return os<<" Simple entropy: "<<s.simpleEntropy()<<" Total: "<<s.total();
}
void printAll (Secret ** secrets, int n) {
for(int i=0;i<n;i++){
cout<<secret[i] //This is printing an address, however that is not what i want.
secrets[i]->print(); //I want that to work like this.
}
}
整个代码:https ://pastebin.com/MDCsqUxJ 我希望第 134 行和第 143 行正常工作。
编辑:
解决方案
secret[i]
是 type Secret*
,你应该先解除引用,然后你的重载将被选中:
cout << *secret[i];
旁注:使用std::vector
而不是原始动态分配。
推荐阅读
- python - “手动”抛出的异常在 PowerShell ISE 中捕获,但不在命令行中
- python - 使用 unittest 框架测试 pandas 数据框
- performance - 我可以依赖 Google Lighthouse 报告(尤其是对于移动网站)吗?
- python - 我正在为这个 python 代码苦苦挣扎(我是初学者)
- javascript - 如何正确注释缓存的mixin
- azure - 从 Azure 帐户中删除所有资源
- c# - YamlDotNet - 自定义序列化
- node.js - NodeJS 中的动态导入(在 Gatsby 中):未指定动态导入回调
- reactjs - React hooks - 当我们刷新页面时从 react-router 位置状态中删除
- axis - 将等距频率轴更改为等距波长轴 - python 3.8