在 C++ 中重载插入运算符
我有一堂课,我试图在其中重载 <<操作员。由于某种原因,它没有超载。
这是我的 .h 文件:
friend std::ostream& operator<<(std::ostream&, const course &); //course is my class object name
在我的 .cpp 中,我将其作为我的实现:
std::ostream& operator<<(std::ostream &out, const course & rhs){
out << rhs.info;
return out;
}
这应该是正确的,但是当我尝试编译它时,它说 cout << tmp; ostream 中未定义。
我已将 iostream 包含在我的 .cpp 和 .h 中,
我一直在绞尽脑汁试图弄清楚这一点。你能看出这有什么问题吗?
编辑: 因为我所做的似乎是正确的,所以这是我的所有源代码: http://pastebin.com/f5b523770< /a>
第 46 行是我的原型,
第 377 行是实现,
第 435 行是我尝试编译它时失败的地方。
另外,我刚刚尝试在另一台机器上编译它,但它给出了以下错误:
course.cpp:246: error: non-member function 'std::ostream& operator<<(std::ostream&, const course&)' cannot have cv-qualifier
make: *** [course.o] Error 1
I have a class in which I'm trying to overload the << operator. For some reason, it is not being overloaded.
Here is my .h file:
friend std::ostream& operator<<(std::ostream&, const course &); //course is my class object name
in my .cpp, I have this as my implementation:
std::ostream& operator<<(std::ostream &out, const course & rhs){
out << rhs.info;
return out;
}
This should be correct, but when I try to compile it, it says that cout << tmp; is not defined in ostream.
I've included iostream in my .cpp and .h
I'm been pulling my hair out trying to figure this out. Can you see anything that's wrong with this?
EDIT:
Since what I'm doing seems to be correct, here's all of my source code: http://pastebin.com/f5b523770
line 46 is my prototype
line 377 is the implementation
line 435 is where it fails when i attempt to compile it.
also, I just tried compiling it on another machine, and it gives this error instead:
course.cpp:246: error: non-member function 'std::ostream& operator<<(std::ostream&, const course&)' cannot have cv-qualifier
make: *** [course.o] Error 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您列出的语法是正确的,但必须在课程定义中声明重载运算符原型才能正常工作。
课程.h
课程.cpp
The syntax you've listed is correct, but the overloaded operator prototype has to be declared in the course definition to work properly.
course.h
course.cpp
对我来说看起来不错。这是我的版本:
course.h
course.cpp
main_file.cpp
It looks fine to me. Here's my version of it:
course.h
course.cpp
main_file.cpp
您应该包括其余的代码,我认为我们看不到问题出在哪里。
以下简单示例有效:
You should include the rest of the code, I don't think we can see where the problem is.
The following trivial example works:
我发现这很有帮助!
我的插入和提取运算符略有不同。
这里定义了:
friend ostream&运算符<<(ostream &fout,数据类型toPrint)
friend istream&运算符>>(istream &fin, datatype &toReadTo)
语法需要准确。
I found this helpful!
My insertion and extraction operators are slightly different.
here they are defined:
friend ostream& operator<<(ostream &fout, datatype toPrint)
friend istream& operator>>(istream &fin, datatype &toReadTo)
the syntax needs to be exact.