在C ++中重载插入运算符 [英] Overloading Insertion Operator in C++
问题描述
我有一个类,我试图重载<<运算符。
这是我的.h文件: friend std :: ostream& operator<<(std :: ostream& const course&); // course是我的类对象名称
在我的.cpp中,我有这个实现: / p>
std :: ostream& operator<<<(std :: ostream& out,const course& rhs){
out< rhs.info;
return out;
}
这应该是正确的,但是当我尝试编译它时, cout < tmp;没有在ostream中定义。
我已经在我的.cpp和.h中包含iostream
我一直在拉我的头发试图想出这一点。你能看到这个错误吗?
编辑:
由于我做的似乎是正确的,这里是我的所有源代码: http://pastebin.com/f5b523770
第46行是我的原型
行377是实现
行435是当我试图编译它时失败的地方。
此外,我只是尝试在另一台机器上编译它,它会产生此错误:
course.cpp:246:error:non-member function'std :: ostream&运算符<<<(std :: ostream& const course&)'不能有cv-qualifier
pre>
make:*** [course.o]错误1
解决方案您列出的语法是正确的,但重载的运算符原型必须在
<$ p $ p>课程{
public:
friend std :: ostream& operator<<(std :: ostream& const course&);
private:
int info;
}
course.cpp
$ b
std :: ostream& operator<<<(std :: ostream& out,const course& rhs){
out< rhs.info;
return out;
}
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
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
class course {
public:
friend std::ostream& operator<<(std::ostream&, const course&);
private:
int info;
}
course.cpp
std::ostream& operator<<(std::ostream &out, const course &rhs){
out << rhs.info;
return out;
}
这篇关于在C ++中重载插入运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!