创建一个名为"Person"的类,其中包含姓名(字符串类型)和年龄(整数类型)、性别以及一个指针类型的成绩。实现一个合适的构造函数,添加一个拷贝构造函数(深拷贝),实现一个拷贝赋值函数(深拷贝),用于将一个对象的属性值复制给另一个对象。
#include <iostream>
using namespace std;
class Person
{
string name;
int age;
string sex;
int * score;
public:
Person()=default;
Person(string n,int a,string s,int e);
Person(Person & Other);
Person & operator=(const Person & Other);
void show();
~Person();
};
int main()
{
Person p1("zhang",19,"man",88);
p1.show();
Person p2(p1);
p2.show();
Person p3("wang",18,"woman",76);
p3.show();
p3=p1;
p3.show();
Person p4;
p4=p3;
p4.show();
return 0;
}
Person::Person(string n, int a, string s, int e)
{
name=n;
age=a;
sex=s;
score=new int(e);
}
Person::Person(Person &Other)
{
this->name=Other.name;
this->age=Other.age;
this->sex=Other.sex;
this->score=new int(*(Other.score));
cout<<"copy constructor"<<endl;
}
Person &Person::operator=(const Person &Other)
{
this->name=Other.name;
this->age=Other.age;
this->sex=Other.sex;
this->score=new int(*(Other.score));
cout<<"copy assign"<<endl;
return *this;
}
void Person::show()
{
cout<<"name:"<<name<<","<<"age:"<<age<<","<<"sex:"<<sex<<","<<"score:"<<*(score)<<endl;
}
Person::~Person()
{
delete score;
}
运行结果

该代码定义了一个Person类,包括姓名、年龄、性别和一个指向整型分数的指针。类中实现了默认构造函数、带有参数的构造函数、拷贝构造函数(深拷贝)和拷贝赋值运算符(深拷贝)。在主函数中创建Person对象并展示了如何使用这些功能。
1396

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



