#include<iostream>
#include<string>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& cout, Person p);
public:
Person(int a);
~Person();
Person& operator=(Person& p)
{
if (age != NULL)
{
delete(age);
age = NULL;
}
this->age = new int(*p.age);
return *this;
}
private:
int* age;
};
ostream& operator<<(ostream& cout, Person p)
{
cout << *p.age << endl;
return cout;
}
Person::Person(int a)
{
this->age = new int(a);
}
Person::~Person()
{
if (age != NULL)
{
delete(age);
age = NULL;
}
}
void test01()
{
Person a(10);
Person b(20);
Person c(30);
a = b = c;
cout << a << b << c;
}
int main()
{
test01();
return 0;
}
this->age = new int(*p.age);
由于age是私有变量,所以不能这么访问,必须增加获取age的函数才行
int getAge() {return age;}
this->age = new int(p->getAge());
ostream& operator<<(ostream& cout, Person p)
{
cout << *p.age << endl;
return cout;
----这里由于p不是指针对象,所以cout<<p.age就可以了
私有变量不能直接访问
把错误提示发上来更容易找