A!ive 2020-03-04 11:00 采纳率: 50%
浏览 221
已采纳

请问为什么转换构造函数和复制构造函数一起写就会报错

#include
using namespace std;
class IntClass
{
private:
int value;
public:
//转换int的转换构造函数
IntClass(int intValue)
{
value = intValue;
}
IntClass(IntClass &p)
{
}
int getValue() const { return value; }
};
int main()
{
IntClass a=1;
a=2;
}
如果去掉复制构造函数报错就消失了,但是a(1)这样然后下面写a=2就没问题。还有就是
#include

using namespace std;
//点类
class Point{
public :
Point(int xx,int yy=0);
// Point(Point &p);
Point(){
x=4;
y=4;
}
int getX(){
return x;
}
int getY(){
return y;
}
private :
int x,y;
};

Point::Point(int xx,int yy)
{
x=xx;
y=yy;
}

//Point::Point(Point &p)
//{
// x=p.x;
// y=p.y;
//}

//线类
class Line{
public :
Line(Point xp1,Point xp2);
Line(Line &m);
double getlen(){
return len;
}
private :
double len;
Point p1,p2;
};

Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2) //
{
cout<<xp1.getX()<<ends<<xp2.getX()<<ends<<p1.getX()<<ends<<p2.getX()<<endl;
len=3;
}
Line::Line(Line &m):p1(m.p1),p2(m.p2)
{
len=m.len;
cout<<len;
}

int main()
{
Point myp1(1,1),myp2(4,5);
Line line(myp1,myp2);
Line line2(line);
myp1=Point(1,4);
myp1=1;
cout<<myp1.getY();
cout << Line(Point(1), Point(4)).getlen() << endl;

}
像这样如果注释掉复制构造函数就没关系不报错但是恢复又会报错,请问这是问什么

  • 写回答

1条回答 默认 最新

  • Eyre Turing 2020-03-04 11:58
    关注

    你复制构造函数写错了
    不是IntClass(IntClass &p)
    而是IntClass(const IntClass &p)
    注意要用const

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档