gpt4 book ai didi

c++ - 好友 && 模板

转载 作者:搜寻专家 更新时间:2023-10-31 00:57:42 30 4
gpt4 key购买 nike

我实际上是在尝试让一个模板类与另一个模板类成为 friend 。类似的东西:

#include  <iostream>

template < typename T >
class Test1 {

private:
static int wantToBeFriend;
};

template < typename T >
int Test1<T>::wantToBeFriend = 1;


template < typename T >
class Test2 {

friend class Test1<T>;

public:
void run() {

std::cout << Test1<T>::wantToBeFriend << std::endl;
}
};

int main()
{
Test1<int> test1;
Test2<int> test2;

test2.run();
return 0;
}

但我做不到,gcc 说 int Test1<T>::wantToBeFriend is private .有人知道如何实现吗?

谢谢

最佳答案

友元并不像您想要的那样运作。当你有

friend class Test1<T>;

这意味着 Test1<T>可以访问 Test2<T> 的私有(private)成员.它不允许 Test2<T>访问 Test1<T>的私有(private)成员。如果是这样,那么拥有私有(private)成员就没有意义了,因为您可以让自己成为类(class)的 friend 并访问他们。

如果我们像这样切换它

template < typename T >
class Test2;

template < typename T >
class Test1 {
friend class Test2<T>;

private:
static int wantToBeFriend;
};

然后代码像现在一样编译得很好Test2<T>可以访问私有(private)成员(Live Example)。

关于c++ - 好友 && 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923711/

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