1.思维导图
2.整理类中特殊成员函数:构造函数、析构函数、拷贝构造函数、拷贝赋值函数的使用和实现。
#include <iostream>
using namespace std;
class Stu
{
string name;
int age;
float score;
public:
//无参构造
Stu()
{
cout << "无参构造" << endl;
}
//析构
~Stu()
{
cout << "析构函数" <<endl;
}
//有参构造
Stu(string name,int age,float score){
this->name=name;
this->age=age;
this->score=score;
cout << "有参构造" << endl;
}
//拷贝构造
Stu(Stu &ptr)
{
this->name=ptr.name;
this->age=ptr.age;
this->score=ptr.score;
cout << "拷贝构造" << endl;
}
//拷贝赋值
Stu &operator=(const Stu &ptr)
{
this->name=ptr.name;
this->age=ptr.age;
this->score=ptr.score;
cout << "拷贝赋值" << endl;
}
void show()
{
cout << name << endl;
cout << age << endl;
cout << score << endl;
}
};
int main()
{
//无参构造
Stu s;
//有参构造
Stu s1("zhangsan",18,90.5);
s1.show();
//拷贝构造函数
Stu s2=s1;
s2.show();
//赋值拷贝
s=s1;
s1.show();
return 0;
}
3.算数运算符重载及赋值运算符重载
#include <iostream>
using namespace std;
class Complex{
int a;
int b;
public:
~Complex()
{
cout << "析构" << endl;
}
Complex()
{
cout << "无参构造" <<endl;
}
Complex(int a,int b)
{
this->a=a;
this->b=b;
cout << "有参构造" <<endl;
}
Complex operator+(Complex &ptr)
{
Complex c;
c.a=this->a+ptr.a;
c.b=this->b+ptr.b;
return c;
}
void show()
{
cout << a <<"+"<< b<< endl;
}
};
int main()
{
Complex c1(3,4);
Complex c2(5,6);
Complex c3=c1+c2;
c3.show();
return 0;
}
#include <iostream>
using namespace std;
class Complex{
int a;
int b;
public:
~Complex()
{
cout << "析构" << endl;
}
Complex()
{
cout << "无参构造" <<endl;
}
Complex(int a,int b)
{
this->a=a;
this->b=b;
cout << "有参构造" <<endl;
}
friend Complex &operator+=(Complex &ptr,Complex &ptr1);
void show()
{
cout << a <<"+"<< b<< endl;
}
};
Complex &operator+=(Complex &ptr,Complex &ptr1)
{
ptr.a+=ptr1.a;
ptr.b+=ptr1.b;
return ptr;
}
int main()
{
Complex c1(3,4);
Complex c2(5,6);
operator+=(c1,c2);
c1.show();
return 0;
}