在一个类上重载 ostream <<并输出另一个类的数据
Overloading ostream << on one class and output data of another class
class Point2D
{
protected:
int x;
int y;
public:
Point2D () {x=0; y=0;}
Point2D (int a, int b) {x=a; y=b;}
void setX (int);
void setY (int);
int getX ();
int getY ();
};
class Line2D
{
friend ostream& operator<< (ostream&, const Line2D&);
private:
Point2D pt1;
Point2D pt2;
double length;
public:
Line2D () {pt1 = Point2D(); pt2 = Point2D();}
Line2D (Point2D ptA, Point2D ptB) {pt1=ptA; pt2=ptB;}
void setPt1 (Point2D);
void setPt2 (Point2D);
Point2D getPt1 ();
Point2D getPt2 ();
};
ostream& operator<< (ostream &out, const Line2D &l)
{
//out << l.length << endl; //Reading length works perfectly
out << l.getPt1().getX() << endl; //But how to read x from pt1 ?
return out;
}
当我运行这些代码时,我得到错误说:
no matching function for call to Line2D::getPt1() const
和
note: candidates are: Point2D Line2D::getPt1() <near match>
.
如果我只是试图通过重载<< operator
来显示length
,它可以完美地工作。但是当我尝试打印类::Point2D的x
和y
时,我得到了错误。
那么打印x
和y
的正确方法应该是什么呢?
操作符(正确地)使用const
引用。因此,通过该引用调用的任何方法都必须是const
。例如,
Point2D getPt1 () const;
^^^^^
您还应该将Point2D
类getter设置为const
.
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 呼叫运营商<<临时
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 过载输出<<用于类的运算符,以打印其中的元组
- 重载运算符<<输出地址而不是数据成员
- 什么会导致死亡<<变量& lt; & lt;“ t";当输出超过终端宽度时,打印空白而不是值
- Can运算符<<用于设计我们自己的输出显示方式