2

这是我的项目的示例代码。

我必须将 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;
}

但是,当我尝试将其交给朋友时,我遇到了错误...请帮助...

4

1 回答 1

3

因为auto_ptr是一个模板类,你需要这样的东西:

friend std::auto_ptr<B>;
于 2012-05-11T09:35:30.290 回答