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

#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;
}

守着星空守着你
浏览 96回答 2
2回答

智慧大石

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

函数式编程

当你在类中自定义了带参数的构造函数,就构成了重载,系统不会调用默认的构造函数,所以要自己定义默认构造函数。除此之外,最后的拷贝构造函数中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;}
打开App,查看更多内容
随时随地看视频慕课网APP