【发布时间】:2015-04-26 23:31:14
【问题描述】:
考虑 bar.h:
#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;
}
为什么 operator 的实现不能访问 Bar 类的私有成员?那就是:
$ 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<<(...,而不是命名空间块。如果它与预先声明的函数不匹配,则具有编译错误的优点
标签: c++ namespaces operator-overloading ostream