/*(2)(多重继承)定义一个工人类Worker,
保护数据成员:char name[20];
公有成员: Worker(char s[]);构造函数
void show();输出数据成员信息。
定义一个儿童类Children,
保护数据成员:int age;
公有成员: Children(int a);构造函数
void show1();输出数据成员信息。
定义一个童工类Clabourer,公有继承工人类和儿童类,
私有成员:char hometown[20];
公有成员: Clabourer(char s[], int a,char ht[]);构造函数
void show2();输出数据成员信息。
在主函数中,用童工类创建对象姓名为小明,年龄为14岁,籍贯为A市,并输出童工的信息。
*/
#include <iostream>
using namespace std;
class Worker//工人类
{
protected:
char name[20];
public:
Worker(char s[]);//构造函数
void show();//输出数据成员信息。
};
Worker::Worker(char s[])
{
int k = 0;//记录s字符的个数
while (s != '\0')
{
s++;
k++;
}
for (int i = 0; i < k; i++)
{
name[i] = s[i];
}
}
void Worker::show()
{
cout << "姓名为:" <<name<< endl;
}
class Children
{
protected:
int age;
public:
Children(int a)//构造函数
{
age = a;
}
void show1()//输出数据成员信息
{
cout << "年龄为:" << age << endl;
}
};
class Clabourer :public Worker, Children//童工类
{
private:
char hometown[20];
public:
Clabourer(char s[], int a, char ht[]):Worker(name),Children(age)//构造函数
{
int k = 0;//记录ht字符的个数
while (ht != '\0')
{
ht++;
k++;
}
for (int i = 0; i < k; i++)
{
hometown[i] = ht[i];
}
}
void show2()// 输出数据成员信息。
{
cout << "姓名:" << name<<endl;
cout << "年龄:" << age << "岁" << endl;
cout << "籍贯:" << hometown << endl;
}
};
int main()
{
Clabourer D("小明", 14, "A市");
D.show2();
return 0;
}
s是字符串,不能跟字符比,而字符用作运算时,会转换成ascii码值,比如s!='\0'这样的操作就是拿字符串类型和int类型比,而且char[]类型没有比较运算符操作。
可以这样写: if(!strcmp(s, "\0")) 或者 if(s[0] != '\0')
/*(2)(多重继承)定义一个工人类Worker,
保护数据成员:char name[20];
公有成员: Worker(char s[]);构造函数
void show();输出数据成员信息。
定义一个儿童类Children,
保护数据成员:int age;
公有成员: Children(int a);构造函数
void show1();输出数据成员信息。
定义一个童工类Clabourer,公有继承工人类和儿童类,
私有成员:char hometown[20];
公有成员: Clabourer(char s[], int a,char ht[]);构造函数
void show2();输出数据成员信息。
在主函数中,用童工类创建对象姓名为小明,年龄为14岁,籍贯为A市,并输出童工的信息。
*/
#include <iostream>
#include <cstring>
using namespace std;
class Worker//工人类
{
protected:
char name[20];
public:
Worker(const char s[]);//构造函数
void show();//输出数据成员信息。
};
Worker::Worker(const char s[])
{
int k = strlen(s);
for (int i = 0; i < k; i++)
{
name[i] = s[i];
}
name[k] = '\0';
}
void Worker::show()
{
cout << "姓名为:" << name << endl;
}
class Children
{
protected:
int age;
public:
Children(int a)//构造函数
{
age = a;
}
void show1()//输出数据成员信息
{
cout << "年龄为:" << age << endl;
}
};
class Clabourer :public Worker, Children//童工类
{
private:
char hometown[20];
public:
Clabourer(const char s[], int a, const char ht[]) :Worker(s), Children(a)//构造函数
{
int k = strlen(ht);
for (int i = 0; i < k; i++)
{
hometown[i] = ht[i];
}
hometown[k] = '\0';
}
void show2()// 输出数据成员信息。
{
cout << "姓名:" << name << endl;
cout << "年龄:" << age << "岁" << endl;
cout << "籍贯:" << hometown << endl;
}
};
int main()
{
Clabourer D("小明", 14, "A市");
D.show2();
return 0;
}