问题及代码
/*
ALL rights reserved.
*文件名称: 初学对象11
作者:李长鸿
*完成时间:2015.5.24
*问题描述: 指针型字符串问题
*/
#include<iostream>
#include<cstring>
#include <iomanip>
using namespace std;
class CPerson
{
protected:
char* m_szName;
char* m_szID;
int m_nSex;//0:women,1:man
int m_nAge;
public:
CPerson(char*name,char*id,int sex,int age):m_nSex(sex),m_nAge(age)
{
m_szName=new char[strlen(name)+1];
strcpy(m_szName,name);
m_szID=new char[strlen(id)+1];
strcpy(m_szID,id);
}
void Show1()
{
cout<<"name: "<<m_szName<<'\t'<<"ID: "<<m_szID<<'\t'<<"sex: "<<m_nSex<<'\t'<<"age: "<<m_nAge<<'\t';
}
~CPerson()
{
delete []m_szName;delete []m_szID;
cout<<"欢迎使用"<<endl;
}
};
class CEmployee:public CPerson
{
private:
char* m_szDepartment;
double m_Salary;
public:
CEmployee(char* name,char* id,int sex,int age,char* department,double salary):CPerson(name,id,sex,age),
m_Salary(salary) {m_szDepartment=new char[strlen(department)+1];strcpy(m_szDepartment,department);}
void Show2()
{
Show1();
cout<<"department: "<<m_szDepartment<<'\t'<<"salary: "<<m_Salary<<endl;
}
~CEmployee()
{
delete []m_szDepartment;
cout<<"下次再见"<<endl;
}
};
int main()
{
char name[10],id[19],department[10];
int sex,age;
double salary;
cout<<"input employee's name,id,sex(0:women,1:man),age,department,salary:\n";
cin>>name>>id>>sex>>age>>department>>salary;
CEmployee employee1(name,id,sex,age,department,salary);
employee1.Show2();
return 0;
}
总结:主函数中我直接定义char*name,*id,*department;然后就输入name,id,department. 一直不对。有点昏
本文探讨了在C++中初学者可能遇到的指针型字符串问题,并通过实例代码进行了详细解释。

被折叠的 条评论
为什么被折叠?



