【解決方法】[Solved] テンプレート化されたパラメーターでオペレーターを適切にオーバーロードできないのはなぜですか?


特にこの「<<」とテンプレート化されたパラメーターを使用して、オーバーロードされた演算子を適切に作成するにはどうすればよいですか? 私はそれを実装していましたが、問題は何らかの理由で出力がアドレス/参照であり、カスタムのオーバーロードされた演算子が機能しませんでしたか? そして、宣言のこの2番目のパラメーターがあり、空の型パラメーターを持つこの構文に出くわしました。 コンパイラが文句を言わなかったのはなぜですか? おそらく、このテンプレートを初期化したため、@「何を試しましたか」を参照してください。それでも実行できますが、私にとってはバグのようなもので、意図したとおりに機能しませんでしたか?

std::ostream& operator<<(std::ostream& out, const HashNode</*empty*/>& node) {
    return out << "[ " << "key: " << node.getKey() << ", " << "val: " << node.getValue() << " ]";
}

私が試したこと:

C++
//REM: HashNode.h
template<typename K = int, typename V = std::string>
class HashNode { ... };
template<typename K = int, typename V = std::string>
std::ostream& operator<<(std::ostream& out, const HashNode<K, V>& node) {
    out << "[ " << "key: " << node.getKey() << ", " << "val: " << node.getValue() << " ]";
    return out;
}

//REM: then we stream it out
//HashNode<float, int> hNodeF = new HashNode<float, int>();
HashNode<>* hNode = new HashNode<>();
hNode->setKey(777);
hNode->setValue("lucky?");
std::cout << hNode << std::endl; // why only an address or reference show up, why does my overload operator not working?
delete hNode;

解決策 1

C++
std::cout << *hNode << std::endl;

演算子は参照用に定義されていますが、オブジェクトはポインターです。

解決策 2

ここで良いヘルプを見つけてください。 https://kbrown.hashnode.dev/c-in-computer-science

コメント

タイトルとURLをコピーしました