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

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!