
作业:
#include <iostream>
using namespace std;
class Person
{
private:
int age;
int *p;
public:
//无参构造
Person():p(new int(89))
{
age=18;
cout << age <<endl;
cout << *p <<endl;
}
//有参构造
Person(int age,int num)
{
this->age=age;
this->p=new int(num);
cout <<"age:"<<age<<endl;
cout <<"point:"<<*p <<endl;
}
//拷贝构造函数
Person(Person &oth)
{
age=oth.age;
p=new int(*oth.p);
}
//拷贝赋值函数
Person &operator=(Person &pott)
{
if(this==&pott)
return *this;
age=pott.age;
p=new int (* pott.p);
return *this;
}
//析构函数
~Person()
{
delete p;
p=nullptr;
}
};
int main()
{
Person *p1=new Person(12,43);
Person *p2=new Person();
Person *p3=p1;
return 0;
}
此代码示例展示了C++中类的定义,包括无参构造、有参构造、拷贝构造函数和拷贝赋值运算符的实现。类`Person`含有一个整型成员变量`age`和一个指向整型的指针`p`。程序还演示了动态内存分配以及析构函数用于释放内存的重要性。通过创建并赋值`Person`对象,展示了对象间的复制过程。
5万+

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



