gpt4 book ai didi

c++ - 使 auto_ptr 成为 friend 类

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:51 25 4
gpt4 key购买 nike

这是我项目的示例代码。

我必须将 std::auto_ptr 设为友元类,以便它可以访问私有(private)成员。

  #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;
}

但是当我试图把它发给 friend 时,我遇到了错误......请帮忙....

最佳答案

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

friend std::auto_ptr<B>;

关于c++ - 使 auto_ptr 成为 friend 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10548864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com