首页 > 解决方案 > 如何将重载的 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 行正常工作。

编辑:

标签: c++

解决方案


secret[i]是 type Secret*,你应该先解除引用,然后你的重载将被选中:

 cout << *secret[i];

旁注:使用std::vector而不是原始动态分配。


推荐阅读