首页 > 解决方案 > 打印类类型属性 ( cout << class.property )

问题描述

我正在学习 C++,我有一个关于打印类类型属性的问题。

我正在尝试获取Point(x, y)' 的位置并打印它。

正如我所想的那样,获得位置是完美的工作,但打印却没有。

我认为它应该工作,但它没有,也许我错过了一些东西。

我应该将它转换为可以打印出来的任何其他值类型吗?

所以我刚试过cout << "The position is: " << p1.getPosition();,我得到了一个错误:

prog.cc:29:7: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream'} and 'Point')
   29 |  cout << p1.getPosition();
      |  ~~~~ ^~ ~~~~~~~~~~~~~~~~
      |  |                     |
      |  |                     Point
      |  std::ostream {aka std::basic_ostream}

这是我的代码。

#include <iostream>
using namespace std;

class Point{
    double x;
    double y;
public:
    Point getPosition();
    void setPosition(double x_, double y_);
    Point operator+(const Point& p);
    Point(double x_, double y_)
    {
        x = x_;
        y = y_;
    }
};

Point Point::getPosition(){ return Point(x, y); }
void Point::setPosition(double x, double y){    x = this->x;    y = this->y;    }
Point Point::operator+(const Point& p)
{
    return Point((x+p.x), (y+p.y));
}


int main(void)
{
    Point p1(5.0, 5.0);
    cout << "The position is: " << p1.getPosition() << endl;       //error occured
    return 0;   
}

谢谢你的帮助:)

标签: c++

解决方案


推荐阅读