C – ostream,朋友和命名空间
发布时间:2020-12-16 04:52:23 所属栏目:百科 来源:网络整理
导读:一切都很好,直到我将对象移动到命名空间.现在编译器声称我的Color属性是私有的. 我认为朋友的全部意义是与那些阶级朋友分享封装信息. Color.h friend ostream operator (ostream output,const st::Color color); Color.cpp: ostream operator (ostream outp
一切都很好,直到我将对象移动到命名空间.现在编译器声称我的Color属性是私有的.
我认为朋友的全部意义是与那些阶级朋友分享封装信息. Color.h friend ostream & operator << (ostream& output,const st::Color& color); Color.cpp: ostream & operator <<(ostream& output,const st::Color& color) { output << "Colors:nalphat: " << color.a << "nredt: " << color.r << "ngreent: " << color.g << "nbluet: " << color.b << "nvaluet: " << 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) ===| 那么这笔交易是什么? 我把朋友运算符超载了,它编译得很好.别处没有错误. 它声明如下: 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:nalphat: " << color.a << "nredt: " << color.r << "ngreent: " << color.g << "nbluet: " << color.b << "nvaluet: " << 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 } 没有编译错误,但这种情况在标题中再次使用命名空间是否正常?或者这完全取决于我应该做什么? 编辑: 解决方法
您需要在与对象相同的命名空间中声明和定义运算符.它们仍将通过Argument-Dependent-Lookup找到.
通常的实现将如下所示: /// header file namespace foo { class A { public: A(); private: int x_; friend std::ostream& operator<<(std::ostream& o,const A& a); }; std::ostream& operator<<(std::ostream& o,const A& a); } // foo // cpp file namespace foo { A::A() : x_(23) {} std::ostream& operator<<(std::ostream& o,const A& a){ return o << "A: " << a.x_; } } // foo int main() { foo::A a; std::cout << a << std::endl; return 0; } 编辑 您似乎没有声明您的操作符<<在命名空间中,也在命名空间之外定义它.我调整了代码. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |