
class People
{
protected:
int age;
char* name;
public:
People();
People(int age, const char* name);
~People();
int GetAge() const;
int SetAge(int age);
const char* GetName() const;
int SetName(const char* name);
int CopyPeople(const People& anotherPeople);
}
People::People()
{
age = 0;
name = new char[strlen("NO NAME") + 1];
strcpy(name, "NO NAME");
}
People::People(int age, const char* name)
{
this->age = age;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
People::~People()
{
if (name != NULL)
delete[] name;
}
int People::GetAge() const
{
return age;
}
int People::SetAge(int age)
{
this->age = age;
return 0;
}
const char* People::GetName() const
{
return this->name;
}
int People::SetName(const char* name)
{
if (this->name != NULL)
delete[] this->name;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
return 0;
}
int People::CopyPeople(const People& anotherPeople)
{
// **************請考生完成該函式**************
}
int main()
{
// **************請考生完成該main函式**************
return 0;
uj5u.com熱心網友回復:
供參考:#include<stdio.h>
#include<string.h>
class People
{
protected:
int age;
char* name;
public:
People();
People(int age, const char* name);
~People();
int GetAge() const;
int SetAge(int age);
const char* GetName() const;
int SetName(const char* name);
int CopyPeople(const People& anotherPeople);
};
People::People()
{
age = 0;
name = new char[strlen("NO NAME") + 1];
strcpy(name, "NO NAME");
}
People::People(int age, const char* name)
{
this->age = age;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
People::~People()
{
if (name != NULL)
delete[] name;
}
int People::GetAge() const
{
return age;
}
int People::SetAge(int age)
{
this->age = age;
return 0;
}
const char* People::GetName() const
{
return this->name;
}
int People::SetName(const char* name)
{
if (this->name != NULL)
delete[] this->name;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
return 0;
}
int People::CopyPeople(const People& anotherPeople)
{
//**************請考生完成該函式**************
this->age = anotherPeople.age;
strcpy(this->name,anotherPeople.name);
return 0;
}
int main()
{
// **************請考生完成該main函式**************
People people1(20,"Tom");//(a)創建People物件people1,將其年齡和姓名初始化為20 和 Tom
printf("%s,%d\n",people1.GetName(),people1.GetAge());//(b)輸出people1物件的姓名和年齡
people1.SetName("Jerry");//(c)設定people1物件中的姓名為Jerry
People people2;//(d)宣告一個新的物件people2,使用默認建構式進行初始化
printf("%s,%d\n",people2.GetName(),people2.GetAge());//(e)輸出people2物件的姓名和年齡
people2.CopyPeople(people1); //(f)呼叫CopyPeople函式,將people1中的值拷貝到people2中
printf("%s,%d\n",people2.GetName(),people2.GetAge());//(g)輸出people2物件的姓名和年齡
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/267698.html
標籤:新手樂園
