第10章:类的设计

1,类的拷贝析构等函数的使用
2,源码

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>

/*
1,拷贝构造函数,拷贝赋值运算符,移动构造函数,移动赋值运算符,析构函数
  拷贝和移动构造函数定义了当用同类型的另一个对象初始化本对象时做什么
  拷贝和移动赋值运算符定义了将一个对象赋予同类型的另一个对象时做什么
  析构函数定义了将一个对象销毁时做什么
  2,如果一个构造函数的第一个参数是自身类类型的引用,且任何额外参数都有默认值
   ,则此构造函数是拷贝构造函数
  3,重载运算符:重载运算符本质上是函数,其名字由operator关键字后接表示要定义的运算符的符号
     组成,因此赋值运算符就是一个名为operator=的函数,
*/
using namespace std;
class Sales_data
{
    public:
       ~Sales_data();                                                 //析构函数
    private:
};

Sales_data::~Sales_data()
{

}



class Test_Num1
{
    public:
        Test_Num1(void)                                                //构造函数
        {
            x = 0;
            y = 0;
            cout << "Tset_Num1 Constructor be called" <<endl;
        }

        ~Test_Num1()                                                  //析构函数
        {

        }

        Test_Num1(const Test_Num1 &tc)                                //拷贝构造函数,必须使用引用
        {
            x=tc.x;
            y=tc.y;
            cout << "Test_Num1 Copy Constructor Called" << endl;
        }

        const Test_Num1 &operator = (const Test_Num1 &right)          //赋值构造函数
        {
            x = right.x;
            y = right.y;
            cout << "Tset_Num1 Operator = be Called" << endl;
            return *this;
        }
    private:
        int x, y;
};

class Test_Num2
{
    public:
        Test_Num2()                                                      //构造函数
        {
            cout << "Test_Num2 Constructor be called" <<endl;
        }

        explicit Test_Num2(const Test_Num1 &tcc)                         //显示构造函数
        {
            tc = tcc;
        }

        ~Test_Num2()                                                    //析构函数
        {

        }

        Test_Num2(const Test_Num2 &test_num2): tc(test_num2.tc)        //拷贝构造函数
        {
            tc = test_num2.tc;
            cout << "Test_Num2 Copy Constructor be called" << endl;
        }

        const Test_Num2 &operator = (const Test_Num2 &right)           //赋值构造函数
        {
            tc = right.tc;
            cout << "Test_Num2 Operator = be Called" << endl;

            return *this;
        }
    private:
        Test_Num1 tc;
};

猜你喜欢

转载自blog.csdn.net/ksmtnsv37297/article/details/89444974