【发布时间】:2017-12-10 13:16:45
【问题描述】:
谁能在提供的代码示例中提示我如何正确实现运算符
#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
编辑:
编译器的输出错误(通常好像根本没有定义 operator
g++ -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;}
~~~~~~~~~ ^ ~~~~
【问题讨论】:
-
如果您遇到构建错误,请在问题正文中包含它们(完整、完整且未经编辑)。
-
我认为 typedef 绑定到它们的范围(我可能错了)。您不能将类中的
operator<<重载为友元成员函数(使用friend关键字)吗? -
另外,我不认为 typedef 适用于不总是相同的类型(
template T),在这种情况下我更喜欢using myType = std::map<unsigned int, T>(类型绑定到实例,而不是类) -
@Vivick:至少在类中这样的定义无济于事:编译器不考虑
friend std::ostream& operator<<(std::ostream& stream, MyType const& mm) {return stream;}。
标签: c++ operator-overloading ostream