处理项目我没有启动,我想将<<
运算符添加到类中。问题:班级是其他班级的私人内部班级,后者在namespace
。C++定义内部类的<<运算符
而且我做不到。
问题可以简化这种方式:
#include <iostream>
#include <map>
namespace A {
class B {
private:
typedef std::map<int, int> C;
C a;
friend std::ostream& operator<<(std::ostream& os, const C &c) {
for (C::const_iterator p = c.begin(); p != c.end(); ++p)
os << (p->first) << "->" << (p->second) << " ";
return os;
}
public:
B() {
a[13] = 10;
std::cout << a << std::endl;
}
};
}
int main() {
A::B c;
}
我尝试用g++ test.cpp
编译它:error: no match for ‘operator<<’
。编译器没有找到我的重载函数。我认为在头文件中定义它会更简单,没有运气。如果你认为这样更合适,我也可以在CPP文件中定义这个类,但我不知道该怎么做。
最后一项要求,我不能使用C++ 11(不幸)。
您的代码与Visual C++编译器版本15.0(即VS2008,pre C++ 11)一起使用。你正在使用哪种编译器?在ideone.com上不起作用.... –
我没有在那里看到内部类。只是名称空间中的常规类。 – RedX
@TonyD:好问题,我相应地更新了文字。我用普通的g ++:gcc版本4.8.1(Ubuntu/Linaro 4.8.1-10ubuntu9)。 – unamourdeswann