C++(五十) — 容器中元素满足的条件

  容器中的内容必须满足三个条件:

  • (1)无参构造函数
  • (2)拷贝构造函数
  • (3)重载 = 运算符
#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include<functional>
using namespace std;

class Teacher
{
public:
    Teacher(char *name, int age)
    {
        m_name = new char[strlen(name) + 1];
        strcpy(m_name, name);
        m_age = age;
    }
    ~Teacher()
    {
        if (m_name != nullptr)
        {
            delete[]m_name;
            m_name = nullptr;
            m_age = 0;
        }
    }
    Teacher(const Teacher &obj)
    {
        m_name = new char[strlen(obj.m_name) + 1];
        strcpy(m_name, obj.m_name);
        m_age = obj.m_age;
    }
    // 重载等号操作符
    Teacher& operator+(const Teacher &obj)
    {
        if (m_name != nullptr)
        {
            delete[]m_name;
            m_name = nullptr;
            m_age = 0;
        }
        m_name = new char[strlen(obj.m_name) + 1];
        strcpy(m_name, obj.m_name);
        m_age = obj.m_age;
        return *this;
    }
    void printT()
    {
        cout << m_name << "   " << m_age << endl;
    }
private:
    char *m_name;
    int m_age;
};
/*
//容器必须满足三个条件
(1)无参构造函数
(2)拷贝构造函数
(3)重载 = 运算符
*/
int main()
{
    Teacher t1("t1", 2);
    vector<Teacher> v1;
    v1.push_back(t1);
    t1.printT();

    system("pause");
    return 0;
}

 

posted @ 2019-06-10 11:35  深度机器学习  阅读(429)  评论(0编辑  收藏  举报