2017C++基础——网课笔记(70到72)

七十. 中午回顾(略)
七十一. 不建议重载“并且&&”,“或者||”操作符

#include <iostream>

using namespace std;

class Test
{
public:
    Test(int value){
        this->value = value;
    }

    ~Test(){
        cout<<"~Test()..."<<endl;
    }

    Test operator+ (Test& another){
        cout<<"执行了+操作符重载"<<endl;
        int value_1=this->value + another.value;
        Test temp(value_1);
        return temp;
    }
    /*
    bool operator&& (Test& another)
    {
        cout<<" 执行了&& 操作符重载"<<endl;
        if(this->value && another.value){
            return true;
        }
        else{
            return false;
        }
    }
    */
    bool operator|| (Test &another)
    {
        cout<<"重载了||操作符"<<endl;
        if(this->value || another.value){
            return true;
        }
        else{
            return false;
        }
    }

    friend bool operator&& (Test& t1, Test& t2);

private:
    int value;

};

bool operator&& (Test& t1, Test& t2)
{
    cout<<" 执行了&& 操作符重载"<<endl;
    if(t1.value && t2.value){
        return true;
    }
    else{
        return false;
    }
}

int main()
{
    Test  t1(0);
    Test  t2(20);
    Test  t3 = t1+t2;

    if( t1&& t3){  //t1.operator&&(t1.operator+(t2))
        cout<<"并且运算为真"<<endl;
    }
    else{
        cout<<"并且运算为假"<<endl;
    }


    cout<<"-------------------------"<<endl;

    if( t1 ||t3){  //t1.operator||(t1.operator+(t2))
        cout<<"或运算为真"<<endl;
    }
    else{
        cout<<"或运算为假"<<endl;
    }

    return 0;
}

七十二. 自定义智能指针
#include <iostream>
#include <memory>

using namespace std;

class A
{
public:
    A(int a)
    {
        cout<<"A().... "<<endl;
        this->a = a;
    }

    void func(){
        cout<<"a = "<<this->a<<endl;
    }

    ~A(){
        cout<<"~A().... "<<endl;
    }

private:
    int a;

};

class MyAutoPtr
{
public:

    MyAutoPtr(A* ptr)
    {
        this->ptr=ptr;
    }

    ~MyAutoPtr(){
        if(this->ptr != NULL){
            cout<<"delete ptr"<<endl;
            delete ptr;
            this->ptr=NULL;
        }
    }

    A* operator->()
    {
        return this->ptr;
    }

    A& operator*()
    {
        return *ptr;
    }

private:
    A* ptr;
};

void test1(){
    A *ap= new A(10);

    ap->func();
    (*ap).func();

    delete ap;
}

void test2(){ //这里就不需要delete智能指针的
    auto_ptr<A>ptr(new A(10));

    ptr->func();
    (*ptr).func();

}

void test3()
{
    MyAutoPtr my_p(new A(10));

    my_p->func(); //my_p.ptr->func()
    (*my_p).func(); //*ptr.func();
}

int main()
{
    test1();
    cout<<"-----------------------"<<endl;
    test2();
    cout<<"-----------------------"<<endl;
    test3();




    return 0;
}

展开阅读全文

没有更多推荐了,返回首页