c++ - 打印类类型属性 ( 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;
}
谢谢你的帮助:)
解决方案
推荐阅读
- td-engine - tdengine 数据库中的多级存储
- python - 如何在 twint 中使用 since 和 until 参数?
- python - 如何使用 django 将来自 chromedriver 的文件正确保存在 docker 容器中?
- django - 为什么 Django 开发服务器没有重新加载?
- reactjs - 动态填充菜单组件 - React Material UI
- wordpress - 更改 Wordpress 网站的域名
- python - 直接运行 rasa 服务器,而不是从源环境?
- kubernetes - 在 1.20.8-gke.900 集群中找不到 GKE MultidimPodAutoscaler
- python - 如何让 Django 将图像保存到静态文件中
- ios - iOS 15 Safari 在键盘可见时检测浮动地址栏