2012-05-11 89 views
2

這是我的項目的示例代碼。使auto_ptr成爲朋友類

我必須將std :: auto_ptr設置爲朋友類,以便它可以訪問私有成員。

#include "stdafx.h" 
    #include <map> 
    #include <iostream> 

    //sample namespace 
    namespace test 
    { 
    //class A 
    class A 
    { 
    public: 
     //making class B to friend , so that it can access private members 
     friend class B; 

    private: 
    int i; 

    //constructor - private 
    A(int in) 
     { 
     i = in; 
     } 
     // private destructor; 
     ~A() 
     { 
     std::cout<<"\n Ending"; 
     getchar(); 
    } 
    }; 

    //map to store A pointer 
    typedef std::map<int, std::auto_ptr<A>> MAP; 

    //class B, friend of A 
    class B 
    { 
    private: 
    MAP Map; 
    public: 
    //making auto_ptr to a friend class , so that it can call the destruct all the A  pointer. 
    friend class std::auto_ptr; //Getting error like" error C2990: 'std::auto_ptr' 
//: non-class template has already been declared as a class template 
    B() 
    { 
    std::auto_ptr<A> a(new A(1)); 
    std::auto_ptr<A> b(new A(2)); 
    std::auto_ptr<A> c(new A(3)); 
    Map[0] = a; 
    Map[1] = b; 
    Map[2] = c; 
    } 
    ~B() 
    { 

    } 
}; 
} 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    using namespace test; 
    B ab; 
return 0; 
} 

但是當我試圖使它的朋友我得到錯誤...請幫助....

回答

3

因爲auto_ptr是一個模板類,你需要這樣的:

friend std::auto_ptr<B>;