首页 新闻 会员 周边 捐助

C++错误: error C2558: class 'birth' : no copy constructor available

0
悬赏园豆:50 [已解决问题] 解决于 2012-04-16 22:09

帮朋友问个问题,代码如下;

#include<iostream>
#include <string>
using namespace std;
class birth //定义一个出生日期类
{
public:
birth(int y = 1990, int m = 9, int d =29) //构造
{ year = y, month = m, day = d;}
birth(birth &q); //birth复制构造
int getYear() {return year;}
int getMonth() {return month;}
int getDay() {return day;}
~birth(){} //析构
private:
int year, month, day;
};
birth::birth(birth &q):year(q.year),month(q.month),day(q.day){} //birth复制构造的实现

class people //定义一个人员类,为类的组合
{public:
people() //构造(无参数重载)
{
const string name = "史佑明";const string sex = "";const int oldrear=22;const string id="411381199009292102";
m_name=name;m_sex=sex,m_id=id;m_oldyear=oldrear;
print1();
}
people(const birth &bir, const string &name = "史佑明",const string &sex = "",const int oldyear=22,const string &id="411381199009292102" )/*构造(有参数重载)*/
: m_name(name), m_birthday(bir), m_sex(sex),m_id(id),m_oldyear(oldyear)
{
print2();
}
void print1()//无参重载中成员函数print1()的实现
{
cout <<"原始资料:"<<endl<< "姓名:" << m_name ;
cout << "" << m_sex <<""<<"年龄:"<<m_oldyear<<"";
cout << "出生日期:" << m_birthday.getYear() << "" << m_birthday.getMonth()<<""
<< m_birthday.getDay() <<""<<"";
cout<<"身份证号"<<m_id<<endl;
}
void print2()//有参重载中成员函数print2()的实现
{
cout <<"新增资料:"<<endl<< "姓名:" << m_name ;
cout << "" << m_sex <<""<<"年龄:"<<m_oldyear<<"";
cout << "出生日期:" << m_birthday.getYear() << "" << m_birthday.getMonth()<<""
<< m_birthday.getDay() <<""<<"";
cout<<"身份证号"<<m_id<<endl;
}
people(people &f);//people类复制构造函数
~people(){} //析构
private:
birth m_birthday;
string m_name;
string m_sex;
int m_oldyear;
string m_id;
};
people::people(people &f):m_birthday(f.m_birthday),m_name(f.m_name), m_sex(f.m_sex),m_id(f.m_id),m_oldyear(f.m_oldyear){}
//people类复制构造函数的实现
int main()
{
people p;
cout<<"请输入新增资料信息:姓名:性别: 年龄: 证件号(身份证号):";
cout<<"出生日期:年:月:日:";
string na,se,id;
int od,ye,mo,da;
cin>>na>>se>>od>>id>>ye>>mo>>da;
birth birthday1(ye,mo,da);
people people1(birthday1,na,se,od,id);
return 0;
}

运行后错误:error C2558: class 'birth' : no copy constructor available

C++
artwl的主页 artwl | 专家六级 | 园豆:16736
提问于:2012-03-25 22:15
< >
分享
最佳答案
0
birth(birth &q); //birth  改为  birth(const birth &q); //birth复制构造
相应的
birth::birth(birth &q):year(q.year),month(q.month),day(q.day){} //birth复制构造的实现
改为:
birth::birth(const birth &q):year(q.year),month(q.month),day(q.day){} //birth复制构造的实现

原因:

people(const birth &bir, const string &name = "史佑明",const string &sex = "男",const int oldyear=22,const string &id="411381199009292102" )/*构造(有参数重载)*/: m_name(name), m_birthday(bir), m_sex(sex),m_id(id),m_oldyear(oldyear) 
people的构造函数中传递的是指向const  birth的引用bir,初始化成员列表中m_birthday(bir)调用拷贝构造函数,但是你的拷贝构造函数写的是birth::birth(birth &q),参数是指向birth的引用,无法默认将一个const对象转换为一个非const对象,所以会出错。
收获园豆:50
zsounder | 老鸟四级 |园豆:2819 | 2012-03-26 00:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册