You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类代码无输出问题咨询

C++类代码无输出问题咨询

嘿,我看你这段C++代码遇到了无输出的问题,先把代码规整好,咱们一起找找问题所在:

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;

class Point{
   double m_x,m_y;
public:
   Point(double x=0,double y=0):m_x(x),m_y(y){}
   Point operator+(const Point b)const{return Point(m_x+b.m_x,m_y+b.m_y);}
   Point operator/(double b)const{return Point(m_x/b,m_y/b);}
   const double& X() const{return m_x;}
   const double& Y() const{return m_y;}
   friend istream& operator>>(istream &is, Point& a);
   friend ostream& operator<<(ostream &os,const Point& a);
};

istream& operator>>(istream &is, const Point&a){
  return is>>a.X()>>a.Y();
}
ostream& operator<<(ostream &os,const Point&a){
  return os<<"("<<a.X()<<","<<a.Y()<<")";
}

class PVec{
   vector<Point> m_pts;
public:
   PVec(int n):m_pts(n){}
   const Point& operator[](int idx) const{return m_pts[idx];}
   // 你贴的代码此处未写完,按常规索引逻辑补充了部分内容
};

接下来咱们说说导致无输出(或输入输出逻辑异常)的关键问题:

  • 输入运算符参数错误:operator>>的第二个参数写成了const Point& a,但输入操作需要修改Point对象的成员变量,这里绝对不能加const,得改成Point& a
  • 只读引用无法赋值:就算是友元函数,调用a.X()和a.Y()接收输入也不行——因为X()和Y()返回的是const double&,属于只读引用,没法被赋值。作为友元,你可以直接访问Point的私有成员m_x和m_y,把输入函数改成这样就正常了:
istream& operator>>(istream &is, Point& a){
  return is >> a.m_x >> a.m_y;
}
  • 另外你贴的PVec类代码不完整,如果后续要测试这个类的输出,得先把Point的输入输出逻辑修复好,不然基础的Point对象都没法正确读写,上层的PVec自然也出不来正确结果。

备注:内容来源于stack exchange,提问作者Cat Ball

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 08:08:07