谁能给我一个提示,如何在提供的代码示例中为 MyType 正确实现 operator#include <iostream>#include <map>template <typename T>class A {public: typedef std::map<unsigned int, T> MyType; MyType data; void show();};template <typename T>std::ostream& operator<<(std::ostream& stream, typename A<T>::MyType const& mm){ return stream << mm.size() << "\n";}//template <typename T>//std::ostream& operator<<(std::ostream& stream, std::map<unsigned int, T> const& mm)//{// return stream << mm.size() << "\n";//}template <typename T>void A<T>::show() {std::cout << data;}int main() { A<double> a; a.show(); return 0;}上面的代码不能编译。但是当我将 operator编辑:编译器的输出错误(通常就好像 operatorg++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++14 -MMD -MP -MF"src/ostreamTest.d" -MT"src/ostreamTest.o" -o "src/ostreamTest.o" "../src/ostreamTest.cpp"../src/ostreamTest.cpp:27:31: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'MyType' (aka 'map<unsigned int, double>')) void A<T>::show() {std::cout << data;} ~~~~~~~~~ ^ ~~~~ 最佳答案 问题是非推导的上下文(感谢 PasserBy 提供链接),这使我们无法找到直接的解决方案。一种解决方法可能是将 typedef 移出类,例如:template <typename T>using A_MyType = std::map<unsigned int, T>;template <typename T>class A{public: typedef A_MyType<T> MyType; MyType data; void show();};template <typename T>std::ostream& operator<<(std::ostream& stream, A_MyType<T> const& mm){ return stream << mm.size() << std::endl;}当然,这适用于 std::map,如果它适用于您更复杂的类 - 不可能在不知道更多细节的情况下说......关于c++ - 为类中定义的 typedef 定义 ostream operator<<,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44950470/