pms*_*pms 10 c++ nested operator-overloading nested-class
如何为一个像这样的嵌套私有类重载一个operator <<?
class outer {
private:
class nested {
friend ostream& operator<<(ostream& os, const nested& a);
};
// ...
};
Run Code Online (Sandbox Code Playgroud)
在外部类编译器之外尝试抱怨隐私时:
error: ‘class outer::nested’ is private
Run Code Online (Sandbox Code Playgroud)
Jam*_*nze 13
你也可以成为operator<<朋友outer.或者你可以完全实现它inline的nested,比如:
class Outer
{
class Inner
{
friend std::ostream&
operator<<( std::ostream& dest, Inner const& obj )
{
obj.print( dest );
return dest;
}
// ...
// don't forget to define print (which needn't be inline)
};
// ...
};
Run Code Online (Sandbox Code Playgroud)
小智 7
如果你想在两个不同的文件(hh,cpp)中使用相同的东西,你必须给朋友两次这个函数如下:
HH:
// file.hh
class Outer
{
class Inner
{
friend std::ostream& operator<<( std::ostream& dest, Inner const& obj );
// ...
};
friend std::ostream& operator<<( std::ostream& dest, Outer::Inner const& obj );
// ...
};
Run Code Online (Sandbox Code Playgroud)
CPP:
// file.cpp:
#include "file.hh"
std::ostream &operator<<( std::ostream& dest, Outer::Inner const& obj )
{
return dest;
}
Run Code Online (Sandbox Code Playgroud)