考虑一下 bar.h:
考虑一下 bar.cc 文件:
#include <iostream>
namespace foo {
class Bar {
public:
friend std::ostream& operator <<(std::ostream& output, const Bar&);
private:
int xx_;
};
}
考虑一下 bar.cc 文件:
#include "bar.h"
std::ostream& operator<<(std::ostream& output, const foo::Bar &in) {
output << in.xx_ << std::endl;
return output;
}
为什么不能从Bar类的实现中访问私有成员变量operator <<?即:
$ icpc -c bar.cc
bar.cc(5): error #308: member "foo::Bar::xx_" (declared at line 9 of "bar.h") is inaccessible
output << in.xx_ << std::endl;
^
compilation aborted for bar.cc (code 2)
我通过将 operator << 的实现嵌入到 foo 命名空间中来解决了这个问题,即:
namespace foo {
std::ostream& operator<<(std::ostream& output, const foo::Bar &in) {
output << in.xx_ << std::endl;
return output;
}
}
然而...这是解决问题的正确方法吗?这种方法是否泄露了实现细节?
std::ostream& foo::operator<<(
...,而不是在命名空间块中。这样做的好处是,如果它与预先声明的函数不匹配,会产生编译错误。 - M.M