如何使用成员作为其他类的对象?

时间:2017-01-10 13:44:22

标签: c++ pointers

我想创建sptr的成员变量ABC,它是其他类SmartPointer的对象。然后为该成员变量赋值。

#include<stdio.h>
#include<iostream>
using namespace std;


class SmartPointer
{
    private:
        int *ptr;

    public:
        SmartPointer(int *p);
        int& operator *();
        ~SmartPointer();
};

SmartPointer::SmartPointer(int *p = NULL)
{
    cout<<"Initilaize SmartPointer"<<p<< endl;
    ptr = p;
}

int& SmartPointer:: operator *()
{  
    return *ptr; 
}


SmartPointer::~SmartPointer()
{

    cout<<"De-Initilaize SmartPointer"<<endl;
    delete ptr;
}


class ABC
{
    private:
        int a;
        SmartPointer *sptr;
        int ref;
    public:
        ABC();                           // Simple constructor.
        ABC(int a, int b);               // Parameterized constructor.
     //     ABC(const ABC &obj);             // Copy constructor.
        ~ABC();                          // Destructor.
        void display();                  // Display.
    //  ABC& operator=(const ABC &obj);  // Operator Overload.
};


ABC::ABC() 
{
    ref= 1;
}


ABC::ABC(int a, int b) 
{
    cout << "Parameterized constructor input" << endl;
    // allocate memory for the pointer;
    sptr = new SmartPointer(&a);
    cout << "Parameterized constructor Out"<<sptr << endl;
}

ABC::~ABC(void) 
{
    cout << "Freeing memory!" << endl;
    ref --;
    if(ref==0)
    {  
        //delete sptr;
    }
}


void ABC::display() 
{

}


int main()
{
//  int a = 10;
//  SmartPointer obj1(&a);

    // Normal.
    ABC obj2(1, 2);

    return 0;
}

创建sptr = new SmartPointer(&a);,但如何获得sptr的价值?

0 个答案:

没有答案