在 cpp 中重载<<运算符时出错?不知道为什么?
Error in overloading << operator in cpp ? dont know why?
这是我的完整代码,除了<<
重载之外,一切都很好。有人能告诉我为什么>>
工作正常时会产生错误吗?任何帮助都将不胜感激。
error"请参阅声明<<"
#include<iostream>
#include<conio.h>
using namespace std;
class point
{
private:
int x,y;
public:
point(int x=0, int y=0)
{
this->x = x;
this->y = y;
}
point & operator + (const point &obj)
{
point temp;
temp.x = this->x + obj.x;
temp.y = this->y + obj.y;
return temp;
}
point & operator - (const point &obj)
{
point temp;
temp.x = this->x - obj.x;
temp.y = this->y - obj.y;
return temp;
}
friend point & operator >>(istream in, point obj);
friend point & operator <<(ostream out, point obj);
};
void main()
{
_getch();
}
point & ::operator >> (istream in, point obj)
{
in >> obj.x;
in >> obj.y;
return obj;
}
point & ::operator << (istream out, point obj) // <--- Here is the Problem
{
//out << "( " << obj.x << " , " << obj.y << " )";
return obj;
}
您应该始终返回流引用,而不是点引用。
更新:我认为其他人在评论中指出了实际问题(istream而不是ostream)。此外,您通过值而不是通过引用来传递流。以下是您的代码应该是什么样子:
istream& ::operator >> (istream &in, const point &obj)
{
in >> obj.x;
in >> obj.y;
return in;
}
ostream& ::operator << (ostream &out, const point &obj) // <--- Here is the Problem
{
out << "( " << obj.x << " , " << obj.y << " )";
return out;
}
更新到我的更新:我还想说,点值应该作为常量引用传递,否则你永远无法传递常量点值(假设你想传递)。请参阅我上面的编辑。
还有一点(并非真正相关):除非迫不得已,否则尽量不要让他们成为Point的朋友。x和y值似乎需要在某个时候公开。如果他们可以公开访问,那么运营商就没有理由成为朋友。
函数被声明为接受ostream
,但被定义为接受istream
。这就是错误。
然而,这里有几个问题。
- 您应该通过引用获取流对象,否则您使用的是副本,它们甚至可能无法复制
- 您应该返回对流对象的引用,以允许使用链接运算符
建议过载采用以下形式:
ostream& operator<<(ostream& os, const point& p)
{
os << "(" << p.x << "," << p.y << ")";
return os;
}
你现在可以做以下事情:
point x;
point y;
// ...
std::cout << x << " and " << y << "n";
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- Linux的Cpp上的计时器
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 命名空间中具有.h和.cpp文件的类
- 内置函数可查看CPP中的成员变量
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- Cpp-Tuple使用带有变量的get
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何通过cpp程序运行shell脚本
- 呼叫运营商<<临时
- 使用2个键的cpp-stl::优先级队列排序不正确
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 如何在cpp文件之间切换窗口?在Qt中
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 我需要知道编译器如何在cpp中使用析构函数
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)