亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我想給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 關注
  • 118 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號