【发布时间】:2012-05-01 22:33:02
【问题描述】:
在我将对象移动到命名空间之前,一切都很好。现在编译器声称我的 Color 属性是私有的。
我认为朋友的全部意义在于与班级的朋友分享封装的信息。
颜色.h
friend ostream & operator << (ostream& output, const st::Color& color);
颜色.cpp:
ostream & operator <<(ostream& output, const st::Color& color) {
output << "Colors:\nalpha\t: " << color.a << "\nred\t: " << color.r << "\ngreen\t: " << color.g
<< "\nblue\t: " << color.b << "\nvalue\t: " << color.color();
return output;
}
错误:
Color.h||In function 'std::ostream& operator<<(std::ostream&, const st::Color&)':|
Color.h|52|error: 'unsigned char st::Color::a' is private|
Color.cpp|15|error: within this context|
Color.h|49|error: 'unsigned char st::Color::r' is private|
Color.cpp|15|error: within this context|
Color.h|51|error: 'unsigned char st::Color::g' is private|
Color.cpp|15|error: within this context|
Color.h|50|error: 'unsigned char st::Color::b' is private|
Color.cpp|16|error: within this context|
||=== Build finished: 8 errors, 0 warnings (0 minutes, 1 seconds) ===|
那么交易是什么? 我使用 Code::Blocks 作为我的 IDE。当我在“颜色”参数上使用点运算符时,它甚至不会显示任何属性或方法。这显然是出事的征兆……某处。
我已经去掉了友元运算符重载,它编译得很好。其他地方没有错误。 什么给了?
声明如下:
namespace st{
class Color {
friend ostream & operator << (ostream& output, const st::Color& color);
public:
....
private:
.....
};
};
编辑:
在我的 CPP 中,我现在已经这样做了:
namespace st{
ostream & st::operator <<(ostream& output, const st::Color& color) {
output << "Colors:\nalpha\t: " << color.a << "\nred\t: " << color.r << "\ngreen\t: " << color.g
<< "\nblue\t: " << color.b << "\nvalue\t: " << color.color();
return output;
}
}
st::Color::Color() {
reset();
}
st::Color::Color(const Color& orig) {
a = orig.a;
r = orig.r;
g = orig.g;
b = orig.b;
}
void st::Color::reset() {
a = 0;
r = 0;
g = 0;
b = 0;
}
... etc
}
没有编译错误,但是这种情况在头文件中再次使用命名空间是否正常?或者这完全偏离了我应该做的事情?
编辑: @Rob 也感谢您的意见!
【问题讨论】:
-
“将我的对象移动到命名空间”是什么意思?
-
在命名空间之间移动对象。 IE 命名空间 st{ 类... }
-
不要在
operator<<的定义中再次使用命名空间。这应该没有必要。 -
你的意思是不要将定义放在标题中的命名空间中?编辑:对不起,我的意思是 CPP 不是上面代码中的标题。
-
在 cpp 文件中的 ostream 方法周围添加 st 命名空间声明。请参阅下面的答案(我在 Linux 上使用 g++ 进行了尝试,效果很好)。
标签: c++ overloading ostream