C++友元重载运算符<<

编程入门 行业动态 更新时间:2024-10-23 08:28:15
本文介绍了C++友元重载运算符<<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试重载运算符 <<但我一直有这个错误.我尝试做研究,但没有结果.我有一个 Point2D.h 和一个 Point2D.cpp,有一个友元函数可以重载.以下是我的代码:

I am trying overload the operator << but i keep having this error. I try doing research but with no result. I have a Point2D.h and a Point2D.cpp with a friend functions to overload. Below are my codes:

Point2D.h

#include <string> #include <iomanip> using namespace std; #ifndef Point2D_H #define Point2D_H class Point2D { friend ostream& operator<< (ostream&, Point2D); public: Point2D(); Point2D(int, int); protected: int x; int y; };

点.cpp

#include <string> #include <cmath> #include <iomanip> #include "Point2D.h" Point2D::Point2D() { this->x=0; this->y=0; } Point2D::Point2D(int x, int y) { this->x=x; this->y=y; } ostream& operator<< (ostream &out, Point2D pt) { out << "Point = " <<pt.x; return out; } #endif

以下是我的错误信息,不知道为什么没有匹配该方法

Below are my error message, not sure why there is no match for that method

Point2D.h: In function ‘std::ostream& operator<<(std::ostream&, Point2D)’: Point2D.h:37:9: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘int’) out << pt.x; ^ Point2D.h:37:9: note: candidates are: Point2D.h:35:10: note: std::ostream& operator<<(std::ostream&, Point2D) ostream& operator<< (ostream &out, Point2D pt) ^ Point2D.h:35:10: note: no known conversion for argument 2 from ‘int’ to ‘Point2D’ In file included from Point2D.h:2:0, from Point3D.h:2, from Point3D.cpp:2: /usr/include/c++/4.8/iomanip:235:5: note: template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, std::_Setw) operator<<(basic_ostream<_CharT, _Traits>& __os, _Setw __f)

推荐答案

您需要

#include <iostream>

或者至少

#include <ostream>

另外 2 个建议:

2 other advises:

  • 包含守卫(ifndef、define 和 endif)应该在 的开头和结尾头文件(endif不能在源文件中,而在头文件中)
  • 在标题中添加 using namespace std; 是不好的做法.至少在标题中使用 std:: 前缀.如果您将在源代码中使用 using namespace std; ,这是您的选择.我不会,但这是我个人的选择.
  • the include guards (ifndef, define and endif) should be at the very beginning and at the very end of the header file (the endif MUST NOT be in the source file, but in the header file)
  • Adding using namespace std; in headers is bad practice. Use std:: prefix at least in the header. It's your choice if you'll use using namespace std; in the source. I wouldn't, but it's my personal choice.

更多推荐

C++友元重载运算符&amp;lt;&lt;

本文发布于:2023-06-03 12:17:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473759.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   amp   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!