为了账号安全,请及时绑定邮箱和手机立即绑定

我想给roundtable加上拷贝构造函数,怎么加?自己弄的报错,不懂咋整

我想给roundtable加上拷贝构造函数,怎么加?自己弄的报错,不懂咋整

C++
守着星空守着你 2023-03-15 21:17:05
#include<iostream>#include<iomanip>#include<cstring>#include<cstdio>using namespace std;class circle{double radius;public:circle(double r){radius=r;}double getarea(){double s;s=radius*radius*3.1415926;return s;}};class table{double height;public:table(double h){height=h;}double getheight(){return height;}};class roundtable:public circle,public table{char *color;public:roundtable(double a,double b,char *c=""):circle(a),table(b){color=new char[strlen(c)];strcpy(color,c);}char *getcolor(){return color;}~roundtable(){delete []color;}roundtable(const roundtable&a){color=new char[strlen(c)];strcpy(color,a.color);};};int main(){roundtable rt(0.8,1.2,"黑色");cout<<"圆桌属性数据:"<<endl;cout<<"高度:"<<rt.getheight()<<"米"<<endl;cout<<"面积:"<<rt.getarea()<<"平方米"<<endl;cout<<"颜色:"<<rt.getcolor()<<endl;getchar();return 0;}
查看完整描述

2 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

拷贝构造函数编译可以自己生成 你可以尝试用对象名作为参数来调用

查看完整回答
反对 回复 2023-03-18
?
函数式编程

TA贡献1807条经验 获得超9个赞

当你在类中自定义了带参数的构造函数,就构成了重载,系统不会调用默认的构造函数,所以要自己定义默认构造函数。除此之外,最后的拷贝构造函数中strlen(c)的使用有误。代码修改如下:

#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdio>
using namespace std;
class circle
{
double radius;
public:
circle(){}//增加的默认构造函数
circle(double r)
{radius=r;}
double getarea()
{
double s;
s=radius*radius*3.1415926;
return s;
}
};
class table
{
double height;
public:
table(){}//增加的默认构造函数
table(double h)
{height=h;}
double getheight()
{return height;}
};
class roundtable:public circle,public table
{
char *color;
public:
roundtable(double a,double b,char *c=""):circle(a),table(b)
{
color=new char[strlen(c)];
strcpy(color,c);
}
char *getcolor()
{return color;}
~roundtable(){delete []color;}
roundtable(const roundtable&a)
{color=new char[strlen(a.color)];//此处进行了修改
strcpy(color,a.color);};

};
int main()
{
roundtable rt(0.8,1.2,"黑色");
cout<<"圆桌属性数据:"<<endl;
cout<<"高度:"<<rt.getheight()<<"米"<<endl;
cout<<"面积:"<<rt.getarea()<<"平方米"<<endl;
cout<<"颜色:"<<rt.getcolor()<<endl;
getchar();
return 0;
}


查看完整回答
反对 回复 2023-03-18
  • 2 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信