对于一个类,本身应该有四个默认函数:
1.默认构造
2.默认析构
3.拷贝构造
4、默认赋值运算符operator= (赋值运算符重载函数)
赋值运算符重载函数与拷贝构造函数一样,都是对类的属性进行值拷贝。
#include<iostream>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& cout, Person p);
public:
Person(){}
Person(int a) {
this->A = a;
}
//拷贝构造
Person(const Person& p) {
this->A = p.A;
}
//赋值
void operator=(const Person &p) {
this->A = p.A;
}
private:
int A;
};
//重载左移运算符
ostream& operator<<(ostream &cout,Person p) {
cout << "A=" << p.A;
return cout;
}
void test01()
{
Person p1(0);
Person p2(1);
p2 = p1; //赋值
Person p3(p1); //拷贝构造
cout << "p1=" << p1 << endl;
cout << "p2=" << p2 << endl;
cout << "p3=" << p3 << endl;
}
int