C++_day06_运算符重载_智能指针

1.只有函数运算符可以带缺省函数,其他运算符函数主要由操作符个数确定

2.解引用运算符和指针运算符

示例代码:

#include <iostream>
using namespace std;

class A{
public:
   A(int data = 0):m_data(data)
  {
    cout << "A构造" << endl;
  }

  ~A(void)
  {
    cout << "A析构" << endl;
  }int m_data;

private:

};

class PA{
public:
    PA (A* pa = NULL):m_pa(pa){}
 

   ~PA(void)
   {
     if(m_pa)
      {
      delete m_pa;
      m_pa = NULL;
      }
    }


    A& operator*(void) const
    {
        return *m_pa;
    }
    A* operator->(void) const
    {
        return &**this;  //this是指向对象pa的指针,*this是pa,**this是复用上面解引用的运算符。
    }

private:
    A* m_pa;
    
};

int main(void)
{
    /*
    A* pa = new A(1234);
    (*pa).m_data = 5678;
    cout << pa->m_data << endl;
    delete pa;
    */
    PA pa(new A(1234));
    (*pa).m_data = 5678;
    //pa.operator*().m_data = 5678;
    cout << (*pa).m_data << endl;
    cout << pa->m_data << endl;
    //cout << pa.operator->()->m_data << endl;
    
    return 0;
}

3.智能指针无需手动释放

#include <iostream>
#include <memory>

using namespace std;

class Student{
public:
    Student (string const& name, int age):m_name(name), m_age(age)
    {
        cout << "Student构造" << endl;
    }
    ~Student(void)
    {
        cout << "Student析构" << endl;
    }
    string m_name;
    int m_age;
};

void foo(void)
{
    auto_ptr<Student> ps(new Student("张无忌", 25));
    cout << (*ps).m_name << ", " << ps->m_age << endl;
}

int main(void)
{
    for(int i = 0; i < 3; i++)
        foo();
    return 0;
}

运行结果:

 智能指针其实是做指针的转移,

1.智能指针没有复制语义,只有转移语义。

2.不能用智能指针管理对象数组。

原文地址:https://www.cnblogs.com/lican0319/p/10654614.html