C++操作符重载(二)

1.这里重载了 -> * 构造一个智能指针,在提取复杂对象中一个属性值的时候,也可以使用 * ->等符号 这里叫智能指针.
2.注意类的构造函数中传参的构造写法.

#include <iostream>
using namespace std;

class Test
{
public:
    Test(){
        this->a = 10;
        
        
    }
    void printT(){
        cout<<a<<endl;
    }
private:
    int a;
};

class MyTestPointer
{
public:
    MyTestPointer(){
        
        p = NULL;
    }
    MyTestPointer(Test *p){
      
        this->p = p;
    }
    
    ~MyTestPointer(){
        delete p;
    }
    
    Test *operator->()
    {
        return p;
    }
    
    Test& operator *(){
        return *p;
    }
    
private:
    Test *p;
};




int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    
    
    Test *p = new Test;
    
    p->printT();
    
    
    delete p;
    
    MyTestPointer myp = new Test;  //这里调用的 含有Test *的构造函数  
    
    myp->printT();//重写 ->
    
    
    
    Test(*myp).printT();//重写 * 提取符
    
    
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容